Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create many arrays in one line

Tags:

arrays

ruby

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?

like image 745
sscirrus Avatar asked Jun 16 '11 05:06

sscirrus


2 Answers

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 image 54
Dhruva Sagar Avatar answered Nov 07 '22 11:11

Dhruva Sagar


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 ... = [], [], [], [] ...
like image 28
Marc-André Lafortune Avatar answered Nov 07 '22 13:11

Marc-André Lafortune