InQusitive InQusitive - 5 months ago 29
Ruby Question

What makes the function call?

I was trying to learn

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"
puts "You are again back to the method"

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


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.