Get Proc of current block?

Is there any way to get a hold of the current block? I’ve been playing
around with recursive enumerations and it occurs to me that the most
flexible technique would simply be to reuse the currently running
block.

For example, where this would be the current block:

h = {:a=>1, :b=>{:c=>3}}

h.map{ |k,v| Hash===v ? [k.to_s, v.map(&this)] : [k.to_s,v.to_s] }

#=> {“a”=>“1”, “b”=>{“c”=>“3”}}

On Fri, Aug 27, 2010 at 10:42 AM, Intransition [email protected]
wrote:

 #=> {“a”=>“1”, “b”=>{“c”=>“3”}}

That’s called the Y-combinator, something i wish could be added to
core, but would be afraid of the many nay-sayers who are already
confused by the current number of ways of creating blocks :slight_smile:

def y(*args, &block)
y = lambda{|*args| block.(*args, &y) }
end

p y{|n, acc, &b|
n < 2 ? acc : b.(n-1, n * acc)
}.(5, 1)

On Aug 26, 2010, at 6:42 PM, Intransition wrote:

Is there any way to get a hold of the current block? I’ve been playing
around with recursive enumerations and it occurs to me that the most
flexible technique would simply be to reuse the currently running
block.

Limited, and pure evil:

lambda { |x| p x += 1; redo }[0]

Infinitely increments. redo lets you restart the current block, but
you must manipulate the original args instead of passing 'em. Don’t do
this. :slight_smile:

~ j.

On Aug 27, 1:27 am, Michael F. [email protected] wrote:

}.(5, 1)

Helpful. Thanks. I am considering adding to Facets, but it would have
to be called #Y b/c YAML defines #y.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs