Last Updated: February 25, 2016
·
737
· cpatuzzo

Learn the collection specific methods

Enumerable has a lot of cool things in it and it's often the first place people look when doing anything non-trivial. Don't forget about the collection specific methods, though!

My first pass at a method looked like this:

def random_indices
  even, odd = partition_by_parity
  if even.any?
    [even[rand(even.size)]]
  elsif odd.any?
    if odd.size == 1
      [odd.first]
    else
      i1 = odd[rand(odd.size)]
      odd -= i1
      i2 = odd[rand(odd.size)]

      [i1, i2] 
    end 
  else
    []  
  end 
end

It now looks like this:

def random_indices
  even, odd = partition_by_parity.map(&:shuffle)
  even.any? ? even.take(1) : odd.take(2)
end

Enough said.