Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Using each_slice.to_a

Tags:

each

ruby

I'm trying to subdivide an array into pairs of arrays.

For example: ["A","B","C","D"] should become [["A","B"],["C","D"].

I believe I've succeeded by doing arg.each_slice(2).to_a. But if I were then to do arg.length on the new array I still get 4. I expect to get 2 (in the above example).

In the end, I want to be able to call the first element of arg to be ["A","B"] but at the moment, I am still getting "A".

like image 632
Jglstewart Avatar asked May 29 '12 14:05

Jglstewart


1 Answers

array = ["A", "B", "C", "D"]

array
 => ["A", "B", "C", "D"]

array.each_slice(2).to_a
 => [["A", "B"], ["C", "D"]]

array.each_slice(2).to_a.length
 => 2

Maybe you are expecting that array.each_slice(2).to_a will change your original array, but here you will have new Array object, because each_slice is non-destructive method, like most in ruby.

new_array = array.each_slice(2).to_a
new_array
 => [["A", "B"], ["C", "D"]]
new_array[0]
 => ["A", "B"]
like image 126
Flexoid Avatar answered Sep 29 '22 03:09

Flexoid