产量变量范围 Ruby

Yield variable scope with Ruby

Ruby如何区分 "Kim" 的函数 yield case 和 "Eric" 的函数调用 case 中的代码块 |n|

抱歉,如果这很明显 - 我真的不明白带有函数(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.

据我了解代码块,它显示,"for each argument, put to screen "我的名字是#{that argument}”。Ruby 如何将 "Kim" 传递给 "that argument" 所以它打印 "My name is Kim" 而不是 "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 呢?

您可以将块视为在概念上类似于方法:

def my_block(n)
  puts "My name is #{n}."
end

yield 称呼它:

my_block("Kim")
my_block(name)

换句话说,n是块的参数,它从yield中获取它的值,每次产生一个值时都会触发块的执行。

As I understand the code block, it reads, "for each argument, put to screen "My name is #{that argument}"

没有。从字面上看,它显示为 "pass argument 'Eric' to method yield_name and also pass this block"。您将块传递给方法这一事实毫无意义。该方法可以简单地 不调用 它(也称为 "yielding to block")。因此,在不知道方法实现的情况下,您不能对块调用次数或提供的参数值做出任何假设。

在这种情况下,我们确实知道实现

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 调用它的块两次。首先,使用静态值 ("Kim")。第二次,它只是传递它的参数 name。如果此处没有 yield 语句,您提供的块将被完全忽略(因此,不会打印任何内容)。但是我们确实触发了该块两次并在输出中看到两行。