如何根据其值的索引拆分数组?

时间:2014-01-24 15:29:00

标签: ruby

如何使用不确定的条目拆分数组:

["a","b","c","d","e",...]

进入偶数和奇数数组,如:

["a","c","e",...]

["b","d","f",...]

4 个答案:

答案 0 :(得分:10)

根据评论

编辑

arr = [:foo, :foo, :bar, :baz, :qux, :foo]

evens, odds = arr.partition.with_index{ |_, i| i.even? }

evens # [:foo, :bar, :qux]
odds # [:foo, :baz, :foo]

答案 1 :(得分:1)

澄清后编辑:

您可以这样做:

odds = []
evens = []
array.each_with_index { |el, index| index % 2 == 0 ? evens << el : odds << el }
[odds, evens]

答案 2 :(得分:1)

如果您正在使用Rails,或require 'active_support'可以执行此操作:

a.in_groups_of(2).transpose

答案 3 :(得分:0)

EDITED: 一般解决方案

partitions_number = 2
['a','b','c','d','e'].group_by.with_index { |obj, i| i % partitions_number }.values
=> [["a", "c", "e"], ["b", "d"]]

['a','b','c','d','e'].group_by.with_index { |obj, i| i % 3 }.values
=> [["a", "d"], ["b", "e"], ["c"]]