yield
- 是ruby比較有特色的一個地方,本文將具體理解一下yield的用法。
- 在函數裏面的有一條yield語句,到時候執行的時候可以執行函數類外的block。而且這個block可以有自己的context,感覺有點像callback,又有點像c裏面的宏定義。
def call_block
puts "Start of method"
yield
yield
puts "End of method"
end
call_block { puts "In the block" }
結果 yield 將調用表達式後面的block
輸出:
Start of method In the block In the block End of method
#!/usr/bin/ruby
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
#!/usr/bin/ruby
def test
yield 5
puts "You are in the method test"
yield 100
end
test {|i| puts "You are in the block #{i}"}
這將產生以下結果:
You are in the block 5
You are in the method test
You are in the block 100
在這裏,yield 語句後跟着參數。您甚至可以傳遞多個參數。在塊中,您可以在兩個豎線之間放置一個變量來接受參數。因此,在上面的代碼中,yield 5 語句向 test 塊傳遞值 5 作爲參數。
現在,看下面的語句:
test {|i| puts “You are in the block #{i}”}
在這裏,值 5 會在變量 i 中收到。現在,觀察下面的 puts 語句:
puts “You are in the block #{i}”
這個 puts 語句的輸出是:
You are in the block 5
如果您想要傳遞多個參數,那麼 yield 語句如下所示:
yield a, b
此時,塊如下所示:
test {|a, b| statement}
但是如果方法的最後一個參數前帶有 &,那麼您可以向該方法傳遞一個塊,且這個塊可被賦給最後一個參數。如果 * 和 & 同時出現在參數列表中,& 應放在後面。
#!/usr/bin/ruby
def test(&block)
block.call
end
test { puts "Hello World!"}
這將產生以下結果:
引用塊內容
Hello World!