From: Devin Mullins Date: 2005-12-20T14:57:18+09:00 Subject: Re: is there a way to use a proc like a method? BTW, a more common way in the Ruby world to do the sort of thing it seems you're after is this: class A attr_accessor :av def do(mproc) mproc.call(self) end end a = proc {|obj| obj.av = 111} I see two advantages of that: - You don't break encapsulation, and thus get complete control over your class's interaction with client code. - The Proc created in the client code gets to refer to its own instance variables and methods. And, yes, I agree with the other comments, too. So, here's my new version: class A attr_accessor :av def initialize @av = 10 end def do yield self end end b=A.new b.do {|obj| obj.av = 111} b.av #=> 111 a = lambda {|obj| obj.av = 112} b.do &a b.av #=> 112 Of course, in this simple example, you could just drop the 'def do...end', and say: b = A.new b.av = 111 b.av #=> 111 But I'm guessing that's not what you're after. Devin Ross Bamford wrote: > On Mon, 19 Dec 2005 20:50:44 -0000, hochherz > wrote: > >> is there a way to use a proc like a method? >> >> like: >> >> class A >> def initialize >> @av=10; >> end >> def do(mproc) >> mproc.call(); >> end >> def rt() >> @av; >> end >> end >> >> >> a=proc{@av=111} #something different >> b=A.new >> b.do(a) >> b.rt #return -> 111 >> >> is it possible by makeing subclass of proc to do this? > > > Maybe use: > > def do(mproc) > instance_eval &mproc > end > > instead of 'call' >