Multiply elements in array

Hi,

This is what I have got:

arr = [“abc”, [“def”, “def”, “def”]]

This is what I would like:

arr_final = [[“abc”, “def”], [“abc”, “def”], [“abc”, “def”]]


If I manage to modify arr to
a2 = [[“abc”, “abc”, “abc”], [“def”, “def”, “def”]]
I could simply use .transpose to get arr_final… There might
be other ways too, but unfortunately, I’m still at square 1.

Any ideas?

Cheers, Chris


Dear Chris,

arr = [“abc”, [“def”, “def”, “def”]]
arr_final=[]
arr[1].collect{|x| arr_final<<[arr[0],x]}
p arr_final

Best regards,

Axel

Axel E. wrote:


Wow, that’s super! Thanks, Axel!

I jsut started messing with arr[0].map and regexes, but your solution is
clean and simple! Cheers, CHris

Axel E. wrote:

arr = [“abc”, [“def”, “def”, “def”]]
arr_final=[]
arr[1].collect{|x| arr_final<<[arr[0],x]}
p arr_final

You could also shorten the processing step a bit:

arr_final = arr[1].collect { |x| [arr[0], x] }

A little bit closer to what Chris had in mind would be:

arr[0] = [arr[0]] * arr[1].size
arr_final = arr.transpose

Alternatively and without changing the original array:

arr_final = ([arr[0]] * arr[1].size).zip(arr[1])

Yet another way to do this is available in Ruby 1.8.7/1.9 (I think):

arr_final = [[arr[0]].product(arr[1])

HTH, Matthias.