about lambda and its binding

R

Rolando Abarca

is there a way to specify the binding of a proc created through lambda?

eg:

$ cat test.rb
class A
attr_reader :foo
def initialize
@foo = lambda { do_that_thing }
end
end

class B
def do_that_thing
puts "yeah, do it!"
end

def initialize
a = A.new
a.foo.call
end
end

B.new

$ ruby test.rb
test.rb:4:in `initialize': undefined local variable or method
`do_that_thing' for #<A:0x127f28 @foo=#<Proc:[email protected]:4>>
(NameError)
from test.rb:15:in `call'
from test.rb:15:in `initialize'
from test.rb:19:in `new'
from test.rb:19

So... is there a way to call the lambda defined in A with the binding
of B?
thanks a lot for any hint...
 
M

Mike Gold

Rolando said:
So... is there a way to call the lambda defined in A with the binding
of B?
thanks a lot for any hint...

def initialize
a = A.new
instance_eval(&a.foo)
end
 
B

Brian Adkins

Rolando Abarca said:
is there a way to specify the binding of a proc created through lambda?

eg:

$ cat test.rb
class A
attr_reader :foo
def initialize
@foo = lambda { do_that_thing }
end
end

class B
def do_that_thing
puts "yeah, do it!"
end

def initialize
a = A.new
a.foo.call
end
end

B.new


So... is there a way to call the lambda defined in A with the binding
of B?
thanks a lot for any hint...

Can you provide more context regarding what you're trying to
accomplish? Or are you simply wanting to learn more about Ruby's
semantics?

For example, parameterizing the lambda may do what you want more
simply:

class A
attr_reader :foo
def initialize
@foo = lambda {|x| x.do_that_thing }
end
end

class B
def do_that_thing
puts "yeah, do it!"
end

def initialize
A.new.foo.call(self)
end
end

B.new
 

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

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top