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".
3 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"] 2try
arg = arg.each_slice(2).to_a In ruby methods that change state of there instances usually has !at the end. For example
hash1.merge!(hash2) Try this
1.9.2p180 :015 > ['A', 'B', 'C', 'D'].each_slice(2).to_a[0] => ["A", "B"]
works fine