Ruby Using Each_Slice. To_A

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

1

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

try

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest