I need to do something like the following
我需要做如下的事情。
e = []
m = []
p = []
t = []
...and so on for about 10 different arrays
Is there a way to create all these arrays on one line?
有办法在一行中创建所有这些数组吗?
4 个解决方案
#1
20
You can do it using the following:
你可以使用以下方法:
e,m,p,t... = Array.new(10) { [] }
It turns out
事实证明
[[]]*10
is not the right way to go, [[]]*10
is for repetition and is just repeating the same object []
10 times, so all the variables would end up getting assigned to the same object.
不是正确的方法,[]*10是重复的,只是重复相同的对象[]10次,所以所有的变量最终会被分配给相同的对象。
#2
6
Like multiple variable declaration in one line a1, a2, a3 = 3, 10, 4
就像一行a1 a2 a3 = 3,10,4中的多重变量声明
e, m, p, t ... = [], [], [], [] ...
#3
4
I'm curious at what are those 10 different arrays, because I would suspect they shouldn't be 10 different variables but just one. You don't give any context, so I can only guess, something like the following might better:
我很好奇这10个不同的数组是什么,因为我觉得它们不应该是10个不同的变量,而应该是1个。你没有提供任何背景,所以我只能猜测,以下这样的东西可能更好:
whatever = Hash.new{|h, k| h[k] = []}
whatever[:e] # => []
whatever[:m] << 42
whatever[:m] # => [42]
# etc...
Otherwise, as zomboid wrote:
否则,正如zomboid写道:
e, m, p, t ... = [], [], [], [] ...
#4
3
What all fails
什么都没有
> p, q, r = v = Array.new(3, [])
=> [[], [], []]
> v.map(&:object_id)
=> [70155104393020, 70155104393020, 70155104393020]
> p = q = r = []
=> []
> [p, q, r].map(&:object_id)
=> [70155104367380, 70155104367380, 70155104367380]
What works
什么工作
> p, q, r = v = Array.new(3){ [] }
=> [[], [], []]
> v.map(&:object_id)
=> [70155104731780, 70155104731760, 70155104731740]
#1
20
You can do it using the following:
你可以使用以下方法:
e,m,p,t... = Array.new(10) { [] }
It turns out
事实证明
[[]]*10
is not the right way to go, [[]]*10
is for repetition and is just repeating the same object []
10 times, so all the variables would end up getting assigned to the same object.
不是正确的方法,[]*10是重复的,只是重复相同的对象[]10次,所以所有的变量最终会被分配给相同的对象。
#2
6
Like multiple variable declaration in one line a1, a2, a3 = 3, 10, 4
就像一行a1 a2 a3 = 3,10,4中的多重变量声明
e, m, p, t ... = [], [], [], [] ...
#3
4
I'm curious at what are those 10 different arrays, because I would suspect they shouldn't be 10 different variables but just one. You don't give any context, so I can only guess, something like the following might better:
我很好奇这10个不同的数组是什么,因为我觉得它们不应该是10个不同的变量,而应该是1个。你没有提供任何背景,所以我只能猜测,以下这样的东西可能更好:
whatever = Hash.new{|h, k| h[k] = []}
whatever[:e] # => []
whatever[:m] << 42
whatever[:m] # => [42]
# etc...
Otherwise, as zomboid wrote:
否则,正如zomboid写道:
e, m, p, t ... = [], [], [], [] ...
#4
3
What all fails
什么都没有
> p, q, r = v = Array.new(3, [])
=> [[], [], []]
> v.map(&:object_id)
=> [70155104393020, 70155104393020, 70155104393020]
> p = q = r = []
=> []
> [p, q, r].map(&:object_id)
=> [70155104367380, 70155104367380, 70155104367380]
What works
什么工作
> p, q, r = v = Array.new(3){ [] }
=> [[], [], []]
> v.map(&:object_id)
=> [70155104731780, 70155104731760, 70155104731740]