在一个区块内屈服是什么意思? [英] What does it mean to yield within a block?

查看:38
本文介绍了在一个区块内屈服是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  def any?
    if block_given?
      method_missing(:any?) { |*block_args| yield(*block_args) }
    else
      !empty?
    end
  end

在 ActiveRecord 的这段代码中,块中的 yield 语句的目的是什么?

In this code from ActiveRecord, what is the purpose of a yield statement that exists within a block?

推荐答案

基本上,如果当前方法已经被赋予一个代码块(由调用者,当它被调用时),yield 就会执行传入指定参数的代码块.

Basically if the current method has been given a code-block (by the caller, when it was invoked), the yield executes the code block passing in the specified parameters.

[1,2,3,4,5].each { |x| puts x }

现在 { |x|puts x} 是传递给 Array 的每个方法的代码块(x 是一个参数).Array#each 实现将迭代自身并使用 x = each_element

Now { |x| puts x} is the code-block (x is a parameter) passed to the each method of Array. The Array#each implementation would iterate over itself and call your block multiple times with x = each_element

pseudocode
def each
  #iterate over yourself
    yield( current_element )
end

因此结果

1
2
3
4
5

*block_args 是一种 Ruby 方法,用于接受未知数量的参数作为数组.调用者可以传入具有不同数量参数的块.

The *block_args is a Ruby way to accept an unknown number of parameters as an array. The caller can pass in blocks with different number of arguments.

最后让我们看看块内的 yield 是什么.

Finally let's see what yield within a block does.

class MyClass
  def print_table(array, &block)
    array.each{|x| yield x}
  end
end

MyClass.new.print_table( [1,2,3,4,5] ) { |array_element| 
    10.times{|i| puts "#{i} x #{array_element} = #{i*array_element}" }
    puts "-----END OF TABLE----"
  }

这里 Array#each 将每个元素生成给给 MyClass#print_table...

Here Array#each yields each element to the block given to MyClass#print_table...

这篇关于在一个区块内屈服是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆