InQusitive InQusitive - 20 days ago 6
Ruby Question

What makes the function call?

I was trying to learn

yield
method which was very confusing to me. Finally when I thought I have understood the method ,suddenly this code appears

def test
puts "You are in the method"
yield
puts "You are again back to the method"
yield
end


when I execute a file containing this code, it doesn't print anything. It's understood that no one is calling this method so no output.

But in the same file if I add

test {puts "You are in the block"}


below the test function suddenly it start printing the puts statements.

I don't understand who is calling the method. If
test {..}
block is causing the call shouldn't it execute its content first?

But the ouput is

You are in the method
You are in the block
You are again back to the method
You are in the block

Answer

When you wrote test { puts "You are in the block"}, that was you calling the function. You were calling test, and passing one argument, a block.

Each method can take one block argument implicitly. When you call yield inside a function, that's you saying "Invoke the block argument." So when you called yield twice, you invoked the block argument twice, in between other puts statements.