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 ld_init, :initialize
def initialize &b
puts "Proc::b.class is: #{b.class}"
old_init &b
end
class << self
alias_method 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
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 ld_init, :initialize
def initialize &b
puts "Proc::b.class is: #{b.class}"
old_init &b
end
class << self
alias_method 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