Multiply elements in array

C

Chris Chris

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
 
A

Axel Etzold

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

---------------------------------------------------

Dear Chris,

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

Best regards,

Axel
 
C

Chris Chris

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
 
M

Matthias Reitinger

Axel said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,775
Messages
2,569,601
Members
45,182
Latest member
alexanderrm

Latest Threads

Top