Y
Yannick Turgeon
Hello all,
I'm currently playing with proc and code block as parameter trying to
learn this aspect. Bellow is some code: three sections. The first one
explain by itself what I whant to do, except that I would like to use
classes. The second is the same in my point of view than the first one
and using a class... but it's now doing what I was expecting. The third
one is working but I don' understand why it should be like this.
Anybody can give me the reason?
Thanks.
Yannick
---------------------------------
##### FIRST SECTION #####
puts "First section"
def fn(text)
return proc{|factor| puts text * factor}
end
f = fn("Joe ")
f.call(3) #It prints "Joe Joe Joe ", as expected.
##### SECOND SECTION #####
puts "Second section"
class Bob
def initialize(factor, &block)
@factor = factor
@action = block
end
def run
@action.call(@factor)
end
end
b = Bob.new(3){f}
b.run #It prints nothing [b.run return the function returned by
fn()]
##### THIRD SECTION #####
puts "Third section"
#Redefine run()
class Bob
def run
@action.call.call(@factor) #Why should I call "call"
twice. Isn't @action supposed to be the function returned by fn()?
end
end
b = Bob.new(3){f}
b.run() #It prints "Joe Joe Joe ".
---------------------------------
I'm currently playing with proc and code block as parameter trying to
learn this aspect. Bellow is some code: three sections. The first one
explain by itself what I whant to do, except that I would like to use
classes. The second is the same in my point of view than the first one
and using a class... but it's now doing what I was expecting. The third
one is working but I don' understand why it should be like this.
Anybody can give me the reason?
Thanks.
Yannick
---------------------------------
##### FIRST SECTION #####
puts "First section"
def fn(text)
return proc{|factor| puts text * factor}
end
f = fn("Joe ")
f.call(3) #It prints "Joe Joe Joe ", as expected.
##### SECOND SECTION #####
puts "Second section"
class Bob
def initialize(factor, &block)
@factor = factor
@action = block
end
def run
@action.call(@factor)
end
end
b = Bob.new(3){f}
b.run #It prints nothing [b.run return the function returned by
fn()]
##### THIRD SECTION #####
puts "Third section"
#Redefine run()
class Bob
def run
@action.call.call(@factor) #Why should I call "call"
twice. Isn't @action supposed to be the function returned by fn()?
end
end
b = Bob.new(3){f}
b.run() #It prints "Joe Joe Joe ".
---------------------------------