I\'m re-defining a method in an object in ruby and I need the new method to be a closure. For example:
def mess_it_up(o)
x = \"blah blah\"
def o.to_s
pu
Feature #1082 implemented in Ruby 1.9.2 makes this an easy task with Object#define_singleton_method:
def mess_it_up(o)
x = "blah blah"
# Use Object#define_singleton_method to redefine `to_s'
o.define_singleton_method(:to_s) { x }
end
The concepts involved are still the same as in my previous answer, which provides a more in-depth description of how this works in Ruby's object model, as well as a Object#define_method
definition that is conceptually the same as Ruby 1.9.2's Object#define_singleton_method
.
Other methods that you might find useful for similar tasks: