kar univer kar univer - 4 months ago 9
Ruby Question

How to join multiple arrays in ruby which has equal size

I have the following code:

prices = [["12.34", "23.12"], ["12.22", "66.11", "33.66", "11.11"], ["32.12"]]
names = [["dog", "pog"], ["foo", "bar", "baz", "zed"], ["qwerty"]]
numbers = [["2", "3"], ["12", "33", "444", "3023"], ["33393"]]
pics = [["url", "url"], ["url", "url", "url", "url"], ["url"]]
chars = ["A", "B", "C"]


How to join arrays, that the result array will be:

[["12.34", "dog", "2", "url", "A"], ["23.12", "pog", "3", "url", "A"],
["12.22", "foo", "12", "url", "B"], ["66.11", "bar", "33", "url", "B"],
...
["32.12", "qwerty", "33393", "url", "C"]]


I tryed join arrays through zip method, but result was:

[[["12.34", "23.12"], ["dog", "pog"], ["2", "3"], ["url", "url"], ["A", "B", "C"]]]
...

Answer

Something like this should do the trick:

chars.map.with_index {|char, i| 
  prices[i].zip(names[i], numbers[i], pics[i], [char].cycle)
}.flatten(1)