Pickle Jar

Given a list of names, pick one name at random.

This problem was suggested by CowboyOnRails for use at Spokane Ruby Brigade. For choosing who gets swag resulting from the Brigade’s O'reilly user group sponsorship.


Zeroth Try:

“The Cowboy’s solution”

module PickleJar

  @random = []
  
  def self.add_name(name)
    @random << namecase(name)
    @random.uniq!
    @random
  end
  
  def self.add_names(names)
    if names.kind_of? String
      names = names.split(',')
    elsif !names.kind_of? Array
      raise RuntimeError, "Please use comma delimited string or array with this method."
    end
    @random += names.collect{ |n| namecase(n.strip) }
    @random.uniq!
    @random
  end
  
  def self.remove_name(name)
    @random.delete(namecase(name.to_s))
  end
  
  def self.remove_names(names)
    if names.kind_of? String
      names = names.split(',')
    elsif !names.kind_of? Array
      raise RuntimeError, "Please use comma delimited string or array with this method."
    end
    @random -= names.collect { |n| namecase(n.strip) }
    @random
  end
  
  def self.winner_is
    return "The Pickle Jar is empty..." if @random.length < 1
    mix_it_up
    "THE WINNER IS: (drum roll)...   #{@random.delete_at(0)}"
  end
  
  def self.mix_it_up  # Just for fun...  already random but makes people feel better.
    @random = @random.sort_by{rand}[0..@random.length]
  end

  def self.peek_in_jar
    @random
  end
  
  def self.namecase(name)
    name = name.to_s
    name.strip!
    name.downcase!
    name.gsub(/\b\w/){$&.upcase}
  end

  def self.empty
    @random = []
  end

end

This solution also has tests and a user manual. The rest of Cowboy’s solution is can be found here


My First Try:

A “One Liner”

This solution more closely matches the conventional meaning of “Cowboy code”.

  ruby -e 'a=%W(bob joe chr jan frk crl cbw dog jr );\
    puts "The Winner is: #{a[rand(a.size)]}"'

My Second Try:

“Object Oriented”

This one uses some of the techniques used in other automated voting systems.

class pickle_jar
  initialize(list)
   puts list.pick_a_random_name
  end
  def pick_a_random_name
    "George"
  end
end

My Third Try:

From the previous century: CGI

Forth Try:

Rack, like all the cool kids do things


My Fifth Try:

Javascript (jQuery), the new hotness


Some of these solutions are deployed on the web: