Ruby Using each_slice.to_a

each, ruby

Solution

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"]

Problem

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"`.

Original source