[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

about lambda and its binding

Rolando Abarca

10/17/2008 12:39:00 AM

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:0x00128608@test.rb: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...
--
Rolando Abarca M.



3 Answers

Mike Gold

10/17/2008 1:15:00 AM

0

Rolando Abarca wrote:
>
> 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
--
Posted via http://www.ruby-....

Brian Adkins

10/17/2008 6:36:00 AM

0

Rolando Abarca <funkaster@gmail.com> writes:

> 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

Rolando Abarca

10/17/2008 10:47:00 AM

0

On 16-10-2008, at 22:15, Mike Gold wrote:

> Rolando Abarca wrote:
>>
>> 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

duh... I totally forgot about instance_eval :-)
thanks!!
--
Rolando Abarca M.