Ruby idioms : Add a method to a concrete instance.

Sometimes can be useful to add a method in a specific instance of a class. We can do that with the next code :

 class Person
 end 

 pedro = Person.new
 peter = Person.new

 # inject a method in the instances
 def pedro.hello_world; puts "Hola Mundo"; end

 def peter.hello_world; puts "Hello World"; end 
 
 pedro.hello_world #=> Hola Mundo
 peter.hello_world #=> Hello World

A more useful example, an Array that represent a list of employees that must be sortable by any of the employee attributes : (via Neal Ford)

  employees  = []
  def employees.sort_by_attribute(sym)
    sort {|x, y| x.send(sym) <=> y.send(sym)}
  end
Advertisements

5 comments so far

  1. Morning Brew #76 on

    […] Ruby idioms : Add a method to a concrete instance. […]

  2. erik scheirer on

    Very, very cool and useful. Works great. Thanks for the post!

  3. Drew on

    Still handy, 3 years later. 🙂

  4. totalrecall on

    Helped me to override a method without having to extend the class.
    Thanks.

  5. Tom Maeckelberghe on

    You can also extend an object

    module Pedro
    def hello_world; puts “Hola Mundo”; end
    end

    module Peter
    def hello_world; puts “Hello World”; end
    end

    class Person
    end

    pedro = Person.new
    pedro.extend(Pedro)
    pedro.hello_world #=> “Hola Mundo”

    peter = Person.new
    peter.extend(Peter)
    peter.hello_world #=> “Hello World”


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: