I am trying to run this code. I am trying to pass arguments into inner proc but my code does not run because of this. What am I doing wrong?
def log (descriptionOfProc,proc)
puts "I have started proc #{descriptionOfProc}"
puts "#{descriptionOfProc} is finished, returning #{proc.call}"
end
inner=Proc.new do |x,y|
x+y
end
middle=Proc.new do |x|
log("inner", inner[1, 2])
"check2"
end
outer=Proc.new do |x|
log("middle", middle)
"check3"
end
puts log("outer", outer)
When you call inner[1,2]
inside middle
proc, you're actually executing the function which will return a value 3
then the argument to log
will be "inner", 3
and since 3 does not respond to call
your script fails.
If you want to fix your script your middle proc should look something like this
middle=Proc.new do |x|
log("inner", -> { inner[1, 2] })
"check2"
end
The reason your code was not working was because you were executing the function inner
with []
. You can execute a block in ruby in different ways .call
, .yield
, .()
, []
. As you can see, you were passing in the result of inner instead of the proc itself. By wrapping the call to inner[1,2]
inside another block to be executed later inside log
by doing proc.call
, you delayed inner's execution.