sscirrus
sscirrus

Reputation: 56709

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?

Upvotes: 12

Views: 7352

Answers (4)

Dhruva Sagar
Dhruva Sagar

Reputation: 7307

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.

Upvotes: 22

Sandip Ransing
Sandip Ransing

Reputation: 7733

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] 

Upvotes: 5

jargalan
jargalan

Reputation: 5184

Like multiple variable declaration in one line a1, a2, a3 = 3, 10, 4

e, m, p, t ... = [], [], [], [] ...

Upvotes: 6

Marc-André Lafortune
Marc-André Lafortune

Reputation: 79552

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 ... = [], [], [], [] ...

Upvotes: 5

Related Questions