Ruby Using each_slice.to_a

I am trying to split an array into pairs of arrays.

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

I believe that I managed to do arg.each_slice(2).to_a . But if I then did arg.length in a new array, I still get 4. I expect to get 2 (in the above example).

In the end, I want the first arg element to be ["A","B"] , but at the moment I'm still getting "A" .

+4
source share
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 

You might expect array.each_slice(2).to_a change your original array , but here you will have a new array object, because each_slice is a 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"] 
+14
source

to try

 arg = arg.each_slice(2).to_a 

In ruby ​​methods that change the state of such specimens, it usually has ! in the end. for instance

 hash1.merge!(hash2) 
+1
source

try it

 1.9.2p180 :015 > ['A', 'B', 'C', 'D'].each_slice(2).to_a[0] 

=> ["A", "B"]

works great

0
source

Source: https://habr.com/ru/post/1414911/


All Articles