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"
.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With