Add items to array collection

Hi, I have a hard time figuring out how arrays work. Here is my problem:

~voice=[1,0,0,1,1]
(~of = 6.collect{|i|~voice})

results in this:

[ [ 1, 0, 0, 1, 1 ], [ 1, 0, 0, 1, 1 ], [ 1, 0, 0, 1, 1 ], [ 1, 0, 0, 1, 1 ], [ 1, 0, 0, 1, 1 ], [ 1, 0, 0, 1, 1 ] ]

How can I add several times 0 to the beginning of each array? E.g. two times 0 to the beginning of the first array, five times 0 to the beginning of the second array, three times 0 to the beginning of the third array, so I get:

[ [ 0, 0, 1, 0, 0, 1, 1 ], [ 0, 0, 0, 0, 0, 1, 0, 0, 1, 1 ], [ 0, 0, 0, 1, 0, 0, 1, 1 ], ...

Thank you in advance!

~voice = [1, 0, 0, 1, 1];
~of = ~voice.size.collect{|i| 
	case( 
		{i == 0}, { 0.dup(2) },
		{i == 1}, { 0.dup(5) },
		{i == 2}, { 0.dup(3) }
	) ++ ~voice 
}

Adding things to the array is done with ++ which is concatenation.

2 Likes

Thank you so much Jordan, this is really helpful and will change the way I work with arrays in the future. Thanks again!

Arrays, although seemingly simple, are very powerful and it can be complicated to see how you can use them. The other structure you should look at is Event.

1 Like