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.
In Ruby, methods can take blocks implicitly and explicitly. Implicit block passing works by calling the yield keyword in a method. The yield keyword is special. It finds and calls a passed block, so you don't have to add the block to the list of arguments the method accepts.
Ruby blocks are little anonymous functions that can be passed into methods. Blocks are enclosed in a do / end statement or between brackets {} , and they can have multiple arguments.
A Proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc, and can be called. Proc is an essential concept in Ruby and a core of its functional programming features.
I didn't write -
foo()
stuff like that.
In Ruby, parentheses are optional when calling methods. You can call a method without parentheses. For example, puts
is often called without parentheses like this:
puts "hello"
You are calling your method here:
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
It is unclear what you are asking here. A block doesn't have a name, so "the method with the same name of the block" doesn't make sense. A block is a special argument to a method call. It cannot appear anywhere else except as the last argument of a method call. It cannot be assigned to a variable, it cannot be returned from a method, it cannot be given a name. It is not an object or a value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With