Reference to 'this block'

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.

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]

···

On Mon, Sep 19, 2005 at 06:23:23PM +0900, Brian Candler wrote:

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) }

--
Mauricio Fernandez

Mauricio Fernández wrote:

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

···

On Mon, Sep 19, 2005 at 06:23:23PM +0900, Brian Candler wrote: