Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd (or even) entries in a Ruby Array

Tags:

ruby

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 
like image 538
Dean Smith Avatar asked Oct 23 '09 15:10

Dean Smith


1 Answers

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 
like image 133
glenn jackman Avatar answered Sep 17 '22 19:09

glenn jackman