简体   繁体   中英

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"]
                             .partition
                             .with_index { |_, i| i.even? }

newArrayOne
#⇒ ["zero", "second"]
newArrayOne, newArrayTwo = array.partition.with_index { |_,i| i.even? }
newArrayOne, newArrayTwo = ["zero","first","second","third"]
                             .each_slice(2)
                             .to_a
                             .transpose

or

newArrayOne, newArrayTwo = Hash["zero","first","second","third"]
                             .to_a
                             .transpose

or:

["zero","first","second","third"].each_with_object([[], []]) do |e, acc|
  (acc.first.length <= acc.last.length ? acc[0] : acc[1]) << e
end

and, of course, using flip-flop (my fave):

["zero","first","second","third"].each_with_object([[], []]) do |e, acc|
  flipflop = acc.first.size == acc.last.size
  (flipflop..flipflop ? acc[0] : acc[1]) << e
end

I assumed that, if n = array.size , an array of n/2 elements is to be returned. See my comment on the question.

array = %w| zero first second third fourth fifth |
  #=> ["zero", "first", "second", "third", "fourth", "fifth"]

newArrayOne, newArrayTwo = array.each_slice(array.size/2).to_a.transpose
  #=> [["zero", "third"], ["first", "fourth"], ["second", "fifth"]]

If, however, the array always has exactly four elements:

newArrayOne, newArrayTwo = [[array[0], array[2]], [array[1], array[3]]]
  #=> [["zero", "second"], ["first", "third"]]

The answer in the comments provided by @bjhaid

["zero","first","second","third"].group_by.with_index { |x,i| i % 2 }.values
#=> [["zero", "second"], ["first", "third"]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM