hack-is-art hack-is-art - 4 months ago 31
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?

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