如何使用不确定的条目拆分数组:
["a","b","c","d","e",...]
进入偶数和奇数数组,如:
["a","c","e",...]
和
["b","d","f",...]
答案 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"]]