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

1 Comment so far

  1. Morning Brew #76 on September 19, 2007

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

Leave a reply