Odd (or even) entries in a Ruby Array
a = ('a'..'z').to_a
a.values_at(* a.each_index.select {|i| i.even?})
# => ["a", "c", "e", "g", "i", "k", "m", "o", "q", "s", "u", "w", "y"]
a.values_at(* a.each_index.select {|i| i.odd?})
# => ["b", "d", "f", "h", "j", "l", "n", "p", "r", "t", "v", "x", "z"]
So, as requested
class Array
def odd_values
self.values_at(* self.each_index.select {|i| i.odd?})
end
def even_values
self.values_at(* self.each_index.select {|i| i.even?})
end
end
...
arr = ["0", "1", "2", "3"]
arr.select.each_with_index { |_, i| i.odd? }
arr.select.each_with_index { |_, i| i.even? }
As floum pointed out, in Ruby 2.2 you can simply do:
arr.select.with_index { |_, i| i.odd? }
left,right = a.partition.each_with_index{ |el, i| i.even? }
You can just use this:
(1..6).partition { |v| v.even? } #=> [[2, 4, 6], [1, 3, 5]]
From Ruby docs: Ruby Docs Reference