But apparently this doesn't work in practice, scratch that, hehe.
···
On Tue, Dec 20, 2005 at 06:58:33AM +0900, Jeffrey Moss wrote:
You could also do something like this:
a=proc{@av=111} #something different
a.bind(b).call
-Jeff
On Tue, Dec 20, 2005 at 05:57:47AM +0900, 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?
>
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