I understood how ruby's block
works.
block_test.rb
def foo
yield if block_given?
end
my_block = foo { puts "hello" }
if I run, ruby block_test.rb
. Of course it print 'hello' as you expected.
hello
But my question is when did I execute ruby block? I did not call foo method in anywhere.
I didn't write - foo()
stuff like that.
# I defined `foo` method here as [If a block has been given, execute it.] but did not call.
def foo
yield if block_given?
end
# I also defined block of `foo` as [print 'hello'] and store into `my_block` variable.
# But I did not say execute `foo`. Did I?
my_block = foo { puts "hello" }
So my assumption is.. When you declare block, It implicitly means that it will execute the method with the same name of the block
Please correct me If I am missing something.
foo { puts "hello" }
you're callingfoo
. – Estrus