How to add methods to existing classes

by Frank

A quick and easy tip today. It won’t impress the veteran ruby developer, but it will impress every ruby newcomers, guaranteed!

Say I have a horse racing ruby application that allow people to know information about every competing horses. I have an input box that people can use to enter the name of a horse. Once they click OK, information about the specified horse is displayed to the user.

Instead of going the traditonal route, how about adding a “horse” method to the String class? It could not be easier :

HORSES = [
  {
    :name => "Jolly Jumper",
    :also_known_as => ["Smart Arse","Lucky Luke friend"],
    :speed => 3, :intelligence => 30,
    :favorite_quote => "I am a horse, I don't have quotes"
  },

  {
    :name => "Incredibly Bad",
    :also_known_as => ["Shame","The Pathetic"],
    :speed => 2, :intelligence => 4,
    :favorite_quote => "If you still put your money on me, you only have yourself to blame"
  },

  {
    :name => "Fast And Furious",
    :also_known_as => ["The Strong Rebel","The Furious One"],
    :speed => 50, :intelligence => 15,
    :favorite_quote => "I am fast"
  },

 {
    :name => "Slow and Jerky",
    :also_known_as => ["Tender","Terrible Choice"],
    :speed => 1, :intelligence => 10,
    :favorite_quote => "Pick me once, regret it for a lifetime."
  }
]

class String
  def horse
    res = HORSES.select { |h| h[:name] == self || h[:also_known_as].include?(self)}
    res.first if res.length>0
  end
end

#Then you can do stuff like this :
horse = "Tender".horse
if horse
	puts "#{horse[:name]}, also known as #{horse[:also_known_as].join(", ")}, has a speed of #{horse[:speed]} and an intelligence of #{horse[:intelligence]}. In its free time, this horse like to become all philosophic, look at the sky and say : '#{horse[:favorite_quote]}'"
else
	puts "This horse doesn't exists in our records"
end

Talk about some great syntactic ruby sugar!

Bookmark this post : These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DZone
  • Reddit
  • del.icio.us
  • Digg
  • Furl
  • Technorati
  • StumbleUpon