Ruby 程式設計中的 yield 關鍵詞


在很多情況下,我們希望在方法中多次執行常規表示式,但無需反覆書寫同一表示式。透過 yield 關鍵字可以做到這一點。

我們還可以向 yield 關鍵字傳遞引數,並獲得返回值。現在,我們來看一些示例,瞭解 Ruby 中的 yield 關鍵字如何工作。

示例 1

考慮下面所示的程式碼,我們在其中在方法內部聲明瞭兩個常規 yield 關鍵字,然後呼叫它。

def tuts
   puts "In the tuts method"

   # using yield keyword
   yield
   puts "Again back to the tuts method"
   yield
end
tuts {puts "Yield executed!"}

輸出

它將生成以下輸出 -

In the tuts method
Yield executed!
Again back to the tuts method
Yield executed!

示例 2

現在,我們嘗試在 yield 關鍵字中新增引數。考慮下面所示的程式碼。

def tuts
   yield 2*5
   puts "In the method tuts"
   yield 150
end
tuts {|i| puts "yield #{i}"}

輸出

如果我們在任何 Ruby IDE 上編寫以下程式碼,那麼在終端中將獲得以下輸出。

yield 10
In the method tuts
yield 150

示例 3

現在,我們來看一個示例,其中我們將從 Ruby 中的 yield 返回值。考慮下面所示的程式碼。

def return_value_yield
   tutorials_point = yield
   puts tutorials_point
end
return_value_yield { "Welcome to TutorialsPoint" }

輸出

如果我們在任何 Ruby IDE 上編寫以下程式碼,那麼在終端中將獲得以下輸出。

Welcome to TutorialsPoint

更新於: 25-Jan-2022

435 次瀏覽

開啟你的 職業

完成課程並獲得認證

開始
廣告