gpt4 book ai didi

Ruby-什么时候执行 block ?

转载 作者:行者123 更新时间:2023-12-03 16:11:47 26 4
gpt4 key购买 nike

我了解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



目前尚不清楚您在这里问什么。块没有名称,因此“具有相同名称的方法”没有任何意义。块是方法调用的特殊参数。除作为方法调用的最后一个参数外,它不能出现在其他任何地方。它不能分配给变量,不能从方法中返回,也不能给定名称。它不是对象或值。

关于Ruby-什么时候执行 block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60238721/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com