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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With