Define a method that is a closure in Ruby
- by J. Pablo Fernández
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
    puts x  # Wrong! x doesn't exists here, a method is not a closure
  end
end
Now if I define a Proc, it is a closure:
def mess_it_up(o)
  x = "blah blah"
  xp = Proc.new {||
    puts x  # This works
  end
  # but how do I set it to o.to_s.
  def o.to_s
    xp.call  # same problem as before
  end
end
Any ideas how to do it?
Thanks.