How to add methods to existing classes

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 one"],
    :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 not furious",
    :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 becomes a philosopher, looks at the sky and often says : '#{horse[:favorite_quote]}'"
else
	puts "This horse doesn't exists in our records"
end

Talk about some great syntactic ruby sugar!

5 thoughts on “How to add methods to existing classes

  1. Remember people to be nice in your comments. I have no problem if you formulate a constructive remark but offensive comments will be removed as soon as they get here. You stay polite or you go elsewhere, it’s that simple. Now I will put an emoticon to convince you all that I am not angry: 🙂

  2. class String
    def horse
    HORSES.detect { |h| h[:name] == self || h[:also_known_as].include?(self) }
    end
    end

Leave a Reply

Your email address will not be published. Required fields are marked *