Reference to 'this block'

B

Brian Candler

Hmm, I'm probably being obtuse here, but how do I get a reference to "this
code block" within a code block? I can write:

a = lambda { |x| x < 2 ? 1 : x * a.call(x-1) }
# trouble is, the block is bound to external variable 'a'

b = a
a = nil
puts b.call(5) # fails

I want the object to be self-contained. 'self' doesn't work. Best I can come
up with is to try and hide it:

a = __myfoo = lambda { |x| x < 2 ? 1 : x * __myfoo.call(x-1) }

Is there a better way that this?

Thanks,

Brian.
 
M

Mauricio Fernández

I want the object to be self-contained. 'self' doesn't work. Best I can come
up with is to try and hide it:

a = __myfoo = lambda { |x| x < 2 ? 1 : x * __myfoo.call(x-1) }

You can use the Y combinator or something as simple as

# make sure _l is block-local
a = lambda{ _l = lambda{|x| x < 2 ? 1 : x * _l[x-1]}}[]
p a[5]
_l = 1 # doesn't matter
p a[5]
 
R

Robert Klemme

Mauricio said:
I want the object to be self-contained. 'self' doesn't work. Best I
can come up with is to try and hide it:

a = __myfoo = lambda { |x| x < 2 ? 1 : x * __myfoo.call(x-1) }

You can use the Y combinator or something as simple as

# make sure _l is block-local
a = lambda{ _l = lambda{|x| x < 2 ? 1 : x * _l[x-1]}}[]
p a[5]
_l = 1 # doesn't matter
p a[5]

If you want to be sure use a function:
def t() f = lambda {|x| x < 2 ? 1 : x * f[x - 1]} end => nil
t[10]
=> 3628800

Btw, recursions don't perform well with Ruby so an iterative solution is
usually better.

Kind regards

robert
 

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
474,183
Messages
2,570,968
Members
47,516
Latest member
ChrisHibbs

Latest Threads

Top