Kyle Macey
Kyle Macey

Reputation: 8154

Array Semi-Flattening

Want to convert this:

[["1", "2", "3"], ["4", "5", "6"]]

to this:

["1", "2", "3"], ["4", "5", "6"]

to be passed into Array.product(), and the first array can contain an unknown number of other arrays. for example, the array given may also be

[["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]

And ultimately, I need to pass the argument as:

otherArray.product(["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"])

Thanks ahead of time!

Upvotes: 4

Views: 108

Answers (3)

Fab
Fab

Reputation: 665

I think what would work for you is using Ruby's Array expansion:

a=[[1,2,3],[4,5,6]]
b=[1,2,3].product([1,2,3],[4,5,6])
c=[1,2,3].product(*a)
b == c #This should be true

Basically putting the asterisk (*) in front of the variable will expand all elements in the array into a list of arguments, which is what you want.

Upvotes: 1

Jacob Eggers
Jacob Eggers

Reputation: 9322

otherArray.product(*[["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]]);

* is used in argument list to unpack array contents to arguments (like here) or to pack arguments into an array,like in "def mymethod(*args)"

Reference: http://www.justskins.com/forums/apply-method-to-array-17387.html

Upvotes: 5

Blindy
Blindy

Reputation: 67382

The last line of code aside, the rest of it seems to be solved by using the 0 index:

arr[0]

Upvotes: 0

Related Questions