什么是收益率?

时间:2016-08-08 18:14:30

标签: ruby

Ruby的收益目的是什么?有人可以解释一下吗?我不明白收益率是多少:

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

3 个答案:

答案 0 :(得分:2)

您可以使用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

希望这有帮助!

答案 1 :(得分:1)

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

答案 2 :(得分:1)

可以使用块作为隐式参数调用任何方法。在方法内部,您可以使用带有值的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会引发异常。

相关问题