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 :

Talk about some great syntactic ruby sugar!

  • Frank

    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: :)

  • Justin

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

  • vps

    I think you manage your coding very well, it is tight, and simple. Mine is a mess, so no offensive comment here.

  • Pingback: How to add methods to existing classes()

  • Stained concrete floors

    Hurrah! After all I got a blog from where I know how to genuinely take
    helpful facts regarding my study and knowledge.