is there a way to use a proc like a method?

H

hochherz

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?
 
P

Pit Capitain

hochherz said:
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?

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

Regards,
Pit
 
J

Jeffrey Moss

You could also do something like this:

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

-Jeff
 
D

Devin Mullins

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,649
Latest member
MargaretCo

Latest Threads

Top