hack-is-art hack-is-art - 1 year ago 137
Ruby Question

Ruby .each_slice with condition even and odd indexes of an array

Say I have a Ruby array of the form:

array = ["zero","first","second","third"]

I want to use a method to split this array into 2 new arrays including the even and odd indexes equivalently.

Ideal result is:

newArrayOne = ["zero", "second"]
newArrayTwo = ["first", "third"]

using the condition of even or odd index as a boolean.

Note: The array will have many elements.

(for the guy with the rude comment that believes is the best programmer alive)

I tried each_slice which accepta one argument and other methods that their signature did not let me to get what I want.

If the results provided were using that specific method in question title, say whatever you like!!!

I was not aware of the methods suggested in the comments and answers, this is why I posted and I am not learning Ruby or using Ruby, I just had to do work of other people absent. Happy now?

Answer Source
["zero","first","second","third"].partition.with_index { |_, i| i.even? }
#⇒ [["zero", "second"], ["first", "third"]]

newArrayOne, newArrayTwo = ["zero","first","second","third"]
                             .with_index { |_, i| i.even? }

#⇒ ["zero", "second"]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download