【问题标题】:What is the yield for? [duplicate]收益是为了什么? [复制]
【发布时间】:2016-12-14 14:57:17
【问题描述】:

Ruby 中 yield 的目的是什么?有人可以解释一下吗?我不明白 yield 的作用:

def variable(&block)
    puts 'Here goes:'
    case block.arity
        when 0
            yield
        when 1
            yield 'one'
        when 2
            yield 'one', 'two'
        when 3
            yield 'one', 'two', 'three'
    end
    puts 'Done!'
end

【问题讨论】:

  • 您尝试阅读文档了吗?

标签: ruby


【解决方案1】:

您可以使用 yield 隐式调用该块。如果给定了一个块,您正在定义在哪里调用该块。例如:

def test
   puts "You are in the method"
   yield
   puts "You are again back to the method"
   yield
end
test {puts "You are in the block"}

这将导致

You are in the method
You are in the block
You are again back to the method
You are in the block

希望这会有所帮助!

【讨论】:

    【解决方案2】:

    如果使用块调用方法,则该方法可以yield 使用一些参数控制块(调用块)(如果需要)。

    【讨论】:

      【解决方案3】:

      可以使用块作为隐式参数调用任何方法。在方法内部,您可以使用带有值的 yield 关键字调用块。 然后,一个方法可以使用 Ruby 的 yield 语句一次或多次调用关联的块。因此,任何想要将块作为参数的方法都可以使用 yield 关键字随时执行块:

      =begin  
        Ruby Code blocks are chunks of code between braces or  
        between do..end that you can associate with method invocations  
      =end  
      def call_block  
        puts 'Start of method'  
        # you can call the block using the yield keyword  
        yield  
        yield  
        puts 'End of method'  
      end  
      # Code blocks may appear only in the source adjacent to a method call  
      call_block {puts 'In the block'}  
      

      输出是:

       >ruby p022codeblock.rb  
          Start of method  
          In the block  
          In the block  
          End of method  
          >Exit code: 0  
      

      如果你在调用方法时提供了代码块,那么在方法内部,你可以yield控制到那个代码块——暂停方法的执行;执行块中的代码;并在调用 yield 之后将控制权返回给方法体。如果没有传递代码块并调用yield,Ruby 会引发异常。

      【讨论】:

        猜你喜欢
        • 2010-10-04
        • 2011-02-24
        • 2019-09-19
        • 2013-05-31
        • 2017-05-30
        • 2010-09-06
        • 2019-03-22
        • 2016-12-21
        相关资源
        最近更新 更多