Create many arrays in one line
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?
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.
Like multiple variable declaration in one line a1, a2, a3 = 3, 10, 4
e, m, p, t ... = [], [], [], [] ...
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:
whatever = Hash.new{|h, k| h[k] = []}
whatever[:e] # => []
whatever[:m] << 42
whatever[:m] # => [42]
# etc...
Otherwise, as zomboid wrote:
e, m, p, t ... = [], [], [], [] ...
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]
精彩评论