Odd (or even) entries in a Ruby Array

Viewed 73102

Is there a quick way to get every other entry in an Array in Ruby? Either the odd or even entries values with 0 included in the odd. I'd like to be able to use it like this:

array1 += array2.odd_values

or

puts array2.odd_values.join("-")

for example

Update

This give exactly what I'm after but I'm sure there is a shorter version.

array1.each_with_index do |item,index| 
  if (index %2 ==0) then 
    array2.push(item) 
  end
end
22 Answers
evens = (1..10).each_with_object([]) {|i, a| a << i*2 }
#=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

I suggest the use of Enumerable#Inject function

array = (1..30)    
array.inject({even: [], odd: []}){|memo, element| memo[element.even? ? :even : :odd] << element; memo}

Slightly left field, but I recently needed something I could pass to select as a proc:

def alternator
  gen = [true,false].cycle
  proc { gen.next }
end

self.filter = alternator

# ... elsewhere/much later ...
input = 'a'..'z'
input.select(&filter)

Some may suggest this could even be a case for Enumerator.new or even a Fiber, which would both technically be simpler constructs, but I think at the expense of clarity.

Related