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 
endIt now looks like this:
def random_indices
  even, odd = partition_by_parity.map(&:shuffle)
  even.any? ? even.take(1) : odd.take(2)
endEnough said.
Written by Chris Patuzzo
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #Ruby 
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#

 
 
 
 
