Ruby .each_slice,包含数组的条件偶数和奇数索引

时间:2016-10-14 16:38:23

标签: arrays ruby

假设我有一个表格的Ruby数组:

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

我想使用一种方法将这个数组拆分为2个新数组,包括偶数和奇数索引。

理想的结果是:

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

使用偶数或奇数索引的条件作为布尔值。

注意:数组将包含许多元素。

(对于那些认为是最好的程序员而言仍然存在粗鲁评论的人)

我尝试了each_slice接受一个参数和其他方法,他们的签名不能让我得到我想要的。

如果提供的结果使用了问题标题中的特定方法,请说出您喜欢的任何内容!!!

我不知道评论和答案中建议的方法,这就是我发布的原因,我不是在学习Ruby或使用Ruby,我只是不得不做其他人缺席的工作。快乐了吗?

5 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:5)

newArrayOne, newArrayTwo = array.partition.with_index { |_,i| i.even? }

答案 2 :(得分:2)

newArrayOne, newArrayTwo = ["zero","first","second","third"]
                             .each_slice(2)
                             .to_a
                             .transpose

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

或:

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

,当然,使用flip-flop(我最喜欢的):

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

答案 3 :(得分:0)

我假设,如果n = array.size,则返回一个n/2元素数组。看看我对这个问题的评论。

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

但是,如果数组总是有四个元素:

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

答案 4 :(得分:0)

@bjhaid提供的评论中的答案

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