How is Proc object created from a block?

P

Phil Tomson

So let's say you have a method that takes a block, like so:

def if?(cond, &b)
puts "b is a: #{b.class}"
if cond
b.call
end
cond
end

call it:

if?(true) { puts "yes!" }


We know that "b is a: Proc" will be printed" (along with yes!) so we know that
when we pass a block into a method using the '&' that it 'magically' becomes a
Proc object.

But how exactly does that happen?

I tried modifying the Proc class to find out (thinking that Proc.new must be
called at some point):

class Proc
alias_method :eek:ld_init, :initialize
def initialize &b
puts "Proc::b.class is: #{b.class}"
old_init &b
end
class << self
alias_method :eek:ld_new, :new
def new &b
puts "Proc::new"
old_new &b
end
end
end

if?(true) {puts "yes!"}
#=>b is a: Proc
#=>yes!

It doesn't look like Proc.new was called... So how was the block transformed
into a Proc object?

A bit of background: I'm trying to put some sort of @level class instance var
in Proc so I can determine how deeply nested in Proc's I am at any given
point:

if?(cond){ #level==1
if?(cond2) { #level==2
if?(cond3) { #level==3
}
}
}

To do that I figured I'd need to do it in Proc.new, but it doesn't seem to get
called...

Phil
 

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,965
Messages
2,570,148
Members
46,710
Latest member
FredricRen

Latest Threads

Top