Ruby - 块何时执行?

Ruby - when is block executed?

我了解 ruby 的 block 是如何工作的。

block_test.rb

def foo
  yield if block_given?
end

my_block = foo { puts "hello" }

如果我运行,ruby block_test.rb。当然,它会按您的预期打印 'hello'。

hello

但我的问题是我什么时候执行了ruby块? 我没有在任何地方调用 foo 方法。

我没有写 - foo() 那样的东西。

# 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" }

所以我的假设是.. 当你声明块时,它隐含地意味着它将执行与块同名的方法

如有遗漏请指正

I didn't write - foo() stuff like that.

在Ruby中,调用方法时括号是可选的。您可以调用不带括号的方法。例如,puts 通常不带括号调用,如下所示:

puts "hello"

您正在此处调用您的方法:

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

不清楚你在这里问什么。块没有名称,因此 "the method with the same name of the block" 没有意义。块是方法调用的特殊参数。除了作为方法调用的最后一个参数外,它不能出现在任何其他地方。它不能被分配给一个变量,它不能从一个方法中返回,它不能被赋予一个名字。它不是对象或值。