Ruby - when is block executed?
Asked Answered
S

1

5

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.

Steib answered 15/2, 2020 at 12:23 Comment(2)
I did not call foo method, yes, you did. With foo { puts "hello" } you're calling foo.Estrus
@SebastianPalma Does it mean when I am defining my block and call at the same time?Steib
G
6

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.

Generable answered 15/2, 2020 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.