Define a method that is a closure in Ruby
        Posted  
        
            by J. Pablo Fernández
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by J. Pablo Fernández
        
        
        
        Published on 2010-03-22T20:38:22Z
        Indexed on 
            2010/03/22
            20:41 UTC
        
        
        Read the original article
        Hit count: 329
        
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.
© Stack Overflow or respective owner