(RUBY) Splitting array into array of pairs
Posted: Fri Jun 19, 2015 7:25 pm
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]
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.
Based on the example, will create
[[[xvalue, yvalue], [xvalue, yvalue]], [[xvalue, yvalue], [xvalue, yvalue]], [[xvalue, yvalue]]]
Happy Programming
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