Forum: Ruby is there a way to use a proc like a method?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
hochherz (Guest)
on 2005-12-19 22:59
(Received via mailing list)
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?
Pit C. (Guest)
on 2005-12-19 23:09
(Received via mailing list)
hochherz schrieb:
>   end
>
> is it possible by makeing subclass of proc to do this?

   class A
     def do(mproc)
       instance_eval(&mproc)
     end
   end

Regards,
Pit
Ross B. (Guest)
on 2005-12-19 23:15
(Received via mailing list)
On Mon, 19 Dec 2005 20:50:44 -0000, hochherz
<removed_email_address@domain.invalid> wrote:

>    end
>
> is it possible by makeing subclass of proc to do this?

Maybe use:

     def do(mproc)
       instance_eval &mproc
     end

instead of 'call'
Jeffrey M. (Guest)
on 2005-12-20 00:00
(Received via mailing list)
You could also do something like this:

a=proc{@av=111} #something different
a.bind(b).call

-Jeff
Jeffrey M. (Guest)
on 2005-12-20 00:03
(Received via mailing list)
But apparently this doesn't work in practice, scratch that, hehe.
Devin M. (Guest)
on 2005-12-20 07:59
(Received via mailing list)
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
This topic is locked and can not be replied to.