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
This seems to work.
class Foo
def mess_it_up(o)
x = "blah blah"
o.instance_variable_set :@to_s_proc, Proc.new { puts x }
def o.to_s
@to_s_proc.call
end
end
end
var = Object.new
Foo.new.mess_it_up(var)
var.to_s
The problem is that code in def
is not evaluated until it's run, and in a new scope. So you have to save the block to an instance variable on the object first and retieve it later.
And define_method
doesn't work because it's a class method, meaning you would have to call it on the class of your object, giving that code to ALL instances of that class, and not just this instance.