From: "Aleksi Niemelä" Date: 2001-02-08T19:54:00+09:00 Subject: [ruby-talk:10560] Re: Giving a Proc utility methods? On Thu, 8 Feb 2001, The Other Clemens wrote: > IMHO: The reason for this behavior is, that the block closure "takes" its > binding upon its creation time, which in your case is the "main context" > of the program. True. > This means you would have to define fail() in the global > scope in order to let the block code see it. The block closure object > (class Proc) is just a wrapper consisting of the code (i.e. the block) > and the binding, but it is NOT the scope of the block(-code). > > Don't know whether you like this solution better: > > class Foo > attr :err > > def initialize (&meth) > @err = meth > end > > def fail (msg) > puts msg > end > > def throw_err (msg) > @err[msg, self] > end > end > > # I want to preserve this closure... > bar = "testing..." > > # Example showing the callback works > my_foo = Foo.new {| msg, other | puts msg + bar} > my_foo.throw_err "Trial 1: " > > # Example of what I *wanted* to do... > my_foo = Foo.new {| msg, other | other.fail (msg + bar)} > my_foo.throw_err "Trial 2: " > > > Clemens (the other ;-) Let me reiterate. This runs and is closer to Ben's original idea of being able to define a method to the proc object itself. Ben will probably sort out if any of these versions is what he's after. - Aleksi class Foo attr :err def initialize (&meth) # TRY to add the method? def meth.fail (msg) puts msg end @err = meth end def throw_err (msg) @err[@err, msg] # give "self" as a first param end end # I want to preserve this closure... bar = "testing..." # Example showing the callback works my_foo = Foo.new {|block, msg| puts msg + bar} my_foo.throw_err "Trial 1: " # Example of what I *wanted* to do... my_foo = Foo.new {|block, msg| block.fail msg + bar} my_foo.throw_err "Trial 2: "