Reputation: 297
How do I split an Array with an indefinite entries:
["a","b","c","d","e",...]
Into even and odd arrays like:
["a","c","e",...]
and
["b","d","f",...]
Upvotes: 3
Views: 2517
Reputation: 37507
If you're using Rails or can require 'active_support'
you can do this:
a.in_groups_of(2).transpose
Upvotes: 1
Reputation: 14051
EDITED: general solution
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"]]
Upvotes: 0
Reputation: 22258
Edited based on comment:
arr = [:foo, :foo, :bar, :baz, :qux, :foo]
evens, odds = arr.partition.with_index{ |_, i| i.even? }
evens # [:foo, :bar, :qux]
odds # [:foo, :baz, :foo]
Upvotes: 10
Reputation: 8131
Edit after clarification:
You can do something like this:
odds = []
evens = []
array.each_with_index { |el, index| index % 2 == 0 ? evens << el : odds << el }
[odds, evens]
Upvotes: 1