开发者

Create many arrays in one line

开发者 https://www.devze.com 2023-03-13 13:23 出处:网络
I need to do something like the following e = [] m = [] p = [] t = [] ...and so on for about 10 different arrays

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] 
0

精彩评论

暂无评论...
验证码 换一张
取 消