Page 1 of 1

(RUBY) Splitting array into array of pairs

Posted: Fri Jun 19, 2015 7:25 pm
by tulamide
Just a little line of code for those, that have an array of values they want to organize in pairs.

Say, you have this: [xvalue, yvalue, xvalue, yvalue, xvalue, yvalue, xvalue, yvalue, xvalue, yvalue]

Code: Select all

newarray = myarray.each_slice(2).map {|n| n}


will create [[xvalue, yvalue], [xvalue, yvalue], [xvalue, yvalue], [xvalue, yvalue], [xvalue, yvalue]]

You can have any length of the subarrays by adjusting the number of elements per slice, e.g. each_slice(3) == triplet
Just make sure to add the dummy map. each_slice just returns either an enumerator or nil, so it's needed. You can chain each_slice to create further layers.

Code: Select all

newarray = myarray.each_slice(2).each_slice(2).map {|n| n}

Based on the example, will create
[[[xvalue, yvalue], [xvalue, yvalue]], [[xvalue, yvalue], [xvalue, yvalue]], [[xvalue, yvalue]]]

Happy Programming :)

Re: (RUBY) Splitting array into array of pairs

Posted: Sat Jun 20, 2015 7:38 am
by KG_is_back
Just to add... to reverse the process simply use "flatten"

Code: Select all

newArray=arrayOfPairs.flatten


it will convert:[[xvalue, yvalue], [xvalue, yvalue], [xvalue, yvalue], [xvalue, yvalue], [xvalue, yvalue]]
to [xvalue, yvalue, xvalue, yvalue, xvalue, yvalue, xvalue, yvalue, xvalue, yvalue]
also it will convert: [[[xvalue, yvalue], [xvalue, yvalue]], [[xvalue, yvalue], [xvalue, yvalue]], [[xvalue, yvalue]]]
to [xvalue, yvalue, xvalue, yvalue, xvalue, yvalue, xvalue, yvalue, xvalue, yvalue]

Flatten also accepts an argument, which specifies the depth of flattening:

Code: Select all

newArray=arrayOfPairs.flatten(1)


in this case: [[[xvalue, yvalue], [xvalue, yvalue]], [[xvalue, yvalue], [xvalue, yvalue]], [[xvalue, yvalue]]]
will be converted to: [[xvalue, yvalue], [xvalue, yvalue], [xvalue, yvalue], [xvalue, yvalue], [xvalue, yvalue]]