Extreme112 Extreme112 - 5 months ago 4
Ruby Question

Why does this block not run when it is stored in a proc?

I'm learning ruby and trying to get a better understanding of Blocks, Yield, Procs and Methods and I stumbled upon this example on using yield.

def calculation(a, b)
yield(a, b)
end

x = calculation(5,6) do|a,b|
a + b
end

puts "#{x}"


From what I understand Procs are object that holds a pointer to Blocks. And Blocks need a method to work in the first place. Also, from the way yield is used, I assume yield jumps to the block immediately after the method call.

I assume the code runs this way: calculation(5,6) calls the method calculation(). when the yield instruction executes, a and b are passed to the block after calculation(5,6). To experement and get a better understand I tried doing this.

def calculation(a, b)
yield(a, b)
end

ankh = Proc.new do |a,b|
a + b
end

x = calculation(5,6) *ankh


The error says that no block is given to calculation(). But aren't we giving calculation(5,6) the block ankh? Hopefully my question isn't too confusing.

Answer

You have a syntax error in the line x = calculation(5,6) *ankh. To pass a method as a block, you use the &-operator.

x = calculation(5,6,&ankh)