【发布时间】:2017-03-26 14:24:48
【问题描述】:
Ruby 如何区分代码块|n| 在“Kim”的函数 yield 情况和“Eric”的函数调用情况下?
抱歉,如果这非常明显 - 我真的不明白代码块中带有 function(arg) 调用的 |n| 变量究竟如何影响函数内部 yield 调用?
def yield_name(name)
puts "In the method! Let's yield..."
yield("Kim")
puts "... now in between the yields!"
yield(name)
puts "Block complete! Back in the method."
end
>>> yield_name("Eric") { |n| puts "My name is #{n}." }
In the method! Let's yield... My name is Kim. ... now in between the yields! My name is Eric. Block complete! Back in the method.
根据我对代码块的理解,它显示“对于每个参数,将“我的名字是#{那个参数}”放到屏幕上。Ruby 如何将“Kim”传递给“那个参数”以便打印“我的名字”是金”而不是“金”吗?谢谢。
---------- 编辑
这是一个名称不那么容易混淆的例子:
def double(parameter)
yield parameter
yield 7
end
当我调用时:
>>> double(3) { |n| puts "how? #{n * 2}" }
我得到:
how? 6 #<-- relative to function call(arg) how? 14 #<-- relative to internal functions yield call(arg)
那么 Ruby 是如何知道在 puts 语句中使用 yield 7 的呢?
【问题讨论】: