(RUBY) Splitting array into array of pairs

Post any examples or modules that you want to share here
Post Reply
tulamide
Posts: 2714
Joined: Sat Jun 21, 2014 2:48 pm
Location: Germany

(RUBY) Splitting array into array of pairs

Post 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 :)
"There lies the dog buried" (German saying translated literally)
KG_is_back
Posts: 1196
Joined: Tue Oct 22, 2013 5:43 pm
Location: Slovakia

Re: (RUBY) Splitting array into array of pairs

Post 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]]
Post Reply