Ruby-什么时候执行块?

问题描述 投票:0回答:1

我是Ruby的新手。因此,如果我的问题是一个愚蠢的问题,请原谅。

我了解ruby的block的工作原理。

block_test.rb] >>

def foo
  yield if block_given?
end


my_block = foo { puts "hello" }

如果我跑步,ruby block_test.rb。当然,它会按照您的预期打印“ hello”。

hello

但是我的问题是..我什么时候执行红宝石块???我没有调用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" }

所以我的假设是[当声明块时,它隐含地表示它将以与块相同的名称执行该方法

如果我缺少某些东西,请纠正我。

我是Ruby的新手。所以如果我的问题是愚蠢的问题,请原谅。我了解红宝石块的工作原理。 block_test.rb def foo是否产生block_given? end my_block = foo {如果i ...

ruby closures block
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.