我有一个数组,我需要将它分成两个,一个接一个的场景。
number = [1,2,3,4,5,6,7,8,9]
我需要把它分成两个,如下面的
split1 = [2,4,6,8]
split2 = [1,3,5,7,9]
答案 0 :(得分:2)
对Arup答案的修改:
split1, split2 = [1,2,3,4,5,6,7,8,9].partition.with_index{|_, i| i.odd?}
split1 # => [2, 4, 6, 8]
split2 # => [1, 3, 5, 7, 9]
split1, split2 = %i[a b c d e].partition.with_index{|_, i| i.odd?}
split1 # => [:b, :d]
split2 # => [:a, :c, :e]