57

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
5
  • 1
    Is this for display purposes? If so, and if it's for the web CSS/javascript has a cleaner way of doing this. Oct 23, 2009 at 15:21
  • 1
    This isn't exactly on target, but see my answer to a (vaguely) related question: stackoverflow.com/questions/1611431/small-question-on-scripting/… Note that I included the 0th element in the evens.
    – Telemachus
    Oct 23, 2009 at 15:22
  • 1
    Not for the web I'm afraid. To be honest I'm just avoiding having a loop as I'm sure there will be a clever Ruby way of doing this.
    – Dean Smith
    Oct 23, 2009 at 15:22
  • Is it every other entry or or odd/even entries?
    – JRL
    Oct 23, 2009 at 15:26
  • JRL - Every other entry Essentially I have data that's off the form info_type_a info_type_b info_type_a info_type_b etc. etc. I just want to extract all the info_type_a or info_type_b
    – Dean Smith
    Oct 23, 2009 at 15:31

22 Answers 22

86
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
2
  • Dean, this includes 0 as the evens. This is inherent in using the % 2 (or derivative) approach. I handle that in my reply.
    – ezpz
    Oct 23, 2009 at 17:23
  • 9
    Slightly faster to do: a.values_at(*a.each_index.select(&:even?)) Sep 27, 2012 at 18:39
72

...

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? }
9
  • 1
    I think select and each_with_index need to be the other way around for it to work -and in that case it'll return a list of tuples.
    – Stephen
    Feb 5, 2014 at 10:27
  • 1
    arr.each_with_index.select { |str, i| i.odd? }.map(&:first), will sort out the tuples.
    – Stephen
    Feb 5, 2014 at 10:36
  • 1
    I suggest arr.select.each_with_index { |_, i| i.odd? }, as the first argument to each_with_index is not actually used. Aug 20, 2015 at 20:19
  • 3
    Actually, on Ruby 2.2, you just can go with arr.select.with_index { |_, i| i.odd? }
    – floum
    Sep 20, 2015 at 18:36
  • 1
    @Bart_Judge it is used to indicate an unused argument. Quite a common convention across a few languages. Some more info here: softwareengineering.stackexchange.com/questions/147252/…
    – Damien
    Jan 27, 2020 at 16:51
23
left,right = a.partition.each_with_index{ |el, i| i.even? }
3
  • This is more elegant than the accepted answer IMHO.
    – paul
    Oct 22, 2014 at 0:56
  • Definitely the best answer
    – Peter P.
    Nov 8, 2017 at 22:29
  • Just a FYI, you could use with_index instead of each_with_index in this solution.
    – Travis
    Nov 13, 2020 at 3:44
18

You can just use this:

(1..6).partition { |v| v.even? }  #=> [[2, 4, 6], [1, 3, 5]]

From Ruby docs: Ruby Docs Reference

2
  • 1
    very nice, should be top comment Mar 24, 2015 at 12:27
  • 13
    except it doesn't act on indices, but array elements. wrong.
    – Victor
    Oct 2, 2015 at 15:19
9

Some crazy way using facets:

require 'facets'
array = [1,2,3,4,5]
odd = array.to_h.keys # 1,3,5
even = array.to_h.values.compact # 2,4
8

This will probably never be read, but...

Simple and clean:

array2.map{ |n| n if n % 2 == 0 }.compact # evens

array2.map{ |n| n if n % 2 == 1 }.compact # odds

Just found an even more terse way (gotta love Ruby):

array2.find_all{ |n| n % 2 == 0 } # evens

array2.reject  { |n| n % 2 == 0 } # odds
2
  • 3
    I think he wanted the array elements with odd indicies. This returns the array elements with odd values.
    – Zaz
    Sep 24, 2014 at 13:03
  • 2
    Also, array.find_all(&:odd?) is even terser!
    – Zaz
    Sep 24, 2014 at 13:04
5
dst = []
array.each_slice(2) { |x| dst.push(x[1]) }

should give you an array of the odd indices.

Replace x[1] with x[0] for the even entries.

4
  • Seems to return a nil value >> array1.each_slice(2) { |x| x[1] } => nil >>
    – Dean Smith
    Oct 23, 2009 at 15:56
  • That's an expensive eay to do it. The fastest is just to loop. Oct 23, 2009 at 16:03
  • Hmmm... I guess it doesn't return a new array. Let me edit it. Oct 23, 2009 at 16:30
  • 1
    @Chris: Of course a loop would be the faster, but why not just write it in ASM while we're at it too? Oct 23, 2009 at 16:34
5

For the record:

a = [1,2,3,4,5,6]
h = Hash[*a]
evens = h.keys
odds = h.values

I'm using the 'splat' operator of Array to get comma separated values and pass that to Hash which accepts arguments as alternating keys/values.

0
4
odds = array.each_slice(2).map(&:first)
evens = array.each_slice(2).map(&:last)
1
  • 1
    Close, except doesn't handle an array with an odd length. [1,3,4].each_slice(2).map(&:last) returns [3,4] but we want [3]. Jan 16, 2013 at 22:34
2

Another way to think about it (adds array2 evens to array1):

array1 << array2.values_at(*Array.new(array2.size/2){|i| i*2})
2

This seems like the most Rubyish solution, combining the best of JacobM and glenn jackman's approaches.

module ::Enumerable
  def select_with_index
    index = -1
    select { |x| yield(x, (index += 1)) }
  end
  def odds
    select_with_index {|x,i| i.odd?}
  end
  def evens
    select_with_index {|x,i| i.even?}
  end
end
1

Here's a code snippet that's intended to add a select_with_index method to Enumerable, which would allow you to do

array.select_with_index{|item, i| item if i % 2 == 0} for evens

array.select_with_index{|item, i| item if i % 2 == 1} for odds

2
  • 1
    you could use if i.even? and if i.odd? Oct 23, 2009 at 16:56
  • that (block_given? && self.class == Range || self.class == Array) stuff in that snippet is nuts. Why not just select { |x| index += 1; yield(x, index) } ? Aug 25, 2012 at 4:39
1

My take on the problem, defining simple Array extensions:

class Array
  def odd_values
    (0...length / 2).collect { |i| self[i*2 + 1] }
  end

  def even_values
    (0...(length + 1) / 2).collect { |i| self[i*2] }
  end
end

puts [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ].odd_values.inspect
# => [1, 3, 5, 7, 9]

puts [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ].even_values.inspect
# => [0, 2, 4, 6, 8]

puts [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ].even_values.inspect
# => [0, 2, 4, 6, 8]

puts [ ].even_values.inspect
# => []
1

This might work for you, or then again, not :-)

irb(main):050:0> all = [1,2,3,4,5,6,7,8,9]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
irb(main):051:0> evens = []
=> []
irb(main):052:0> all.each_index do |i| if (i.even?): evens.push(a[i]) end end
=> [1, 2, 3, 4, 5, 6, 7, 8, 9]
irb(main):053:0> evens
=> [1, 3, 5, 7, 9]
1
  • 1
    (i.even?): -> (i.even?); Mar 11, 2012 at 13:22
1
a = [0,1,2,3,4,5,6,7,8,9]

(1...a.size).step(2).collect { |i| a[i] }
=> [1, 3, 5, 7, 9]

(2...a.size).step(2).collect { |i| a[i] }
=> [2, 4, 6, 8]

Of course, considering 0 an odd index creates a little hackery, right? Since you will have adjacent entries that are in effect odd indicies. To compensate for that you can just add the zeroth entry to the result of the first collect. Consider:

[a[0]] + (1...a.size).step(2).collect { |i| a[i] }
=> [0, 1, 3, 5, 7, 9]

You could always compact this further and do something like:

a.values_at(*(1...a.size).step(2))
=> [1, 3, 5, 7, 9]

a.values_at(*(2...a.size).step(2))
=> [2, 4, 6, 8]

The same hack is available to handle the zeroth entry.

2
1
evens = (1..10).each_with_object([]) {|i, a| a << i*2 }
#=> [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
1
a = [1,2,3,4,5]
a.in_groups_of(2).map(&:first) => odds
a.in_groups_of(2).map(&:last) => evens
2
  • in_groups_of is in Rails only. But each_slice in the Ruby standard library is equivalent here. So write a.each_slice(2).map(&:first). Jul 1, 2013 at 21:04
  • 1
    Note that “odds” in this answer (odd numbers in the array a) means the values at even indexes, and “evens” means values at odd indexes. Jul 1, 2013 at 21:13
1

With a blank array A, and a full array H, something like this should work:

H.size.times do |i|
  if i % 2 == 1
    A[i/2] = H[i]
  end
end
0
module Enumerable
  def odd_values
    r = []
    self.each_index {|x| r << self[x] if x%2==0}
    r
  end
end

p ["a", "b" ,"c" ,"d" ,"e"].odd_values  #returns ["a","c","e"]
p ["a", "b" ,"c" ,"d" ,"e"].odd_values.join("-") #returns "a-c-e"

I just reused an approach i used for another question on arrays. :D

0

Don't forget good old friend Array.inject

a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
a.inject([]){|result, item| result << item if item %2 == 1; result}

Should give you odd items.

0

I suggest the use of Enumerable#Inject function

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

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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.