2016-08-08 80 views
0

Ruby中的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 
+5

您是否嘗試閱讀文檔? –

回答

1

如果一個方法是用塊的調用,則該方法可以yield控制塊的一些參數(調用該塊),如果需要的話。

1

任何方法都可以用塊作爲隱式參數來調用。在方法內部,您可以使用yield關鍵字和值調用塊。 然後,方法可以使用Ruby 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會引發異常。

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 

希望這有助於!