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
[...] Ruby idioms : Add a method to a concrete instance. [...]
Very, very cool and useful. Works great. Thanks for the post!
Still handy, 3 years later.
Helped me to override a method without having to extend the class.
Thanks.
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”