Ruby での利回り
Ruby の最もエキサイティングな機能の 1つは、コードのブロックを関数に渡すことです。 Ruby の組み込みキーワードを使用すると、コードのブロックを関数に渡すことができます。
この記事では、Ruby の block と yield について説明します。 また、トピックをより簡単にするために、いくつかの例と説明を見ていきます。
yield は、block を渡すための組み込みキーワードです。 block は中括弧 ({}) で囲まれたコード行です。
このトピックに関連する例を見てみましょう。
Ruby で yield キーワードを使用する
以下の例は、Ruby プログラムでキーワード yield を使用する方法を示しています。 以下のサンプルコードを見てください。
def MyMethod
puts "This is from the method."
# Using the yield keyword
yield
puts "Passing the block again."
yield
end
MyMethod {puts "This is a block."}
上記の例では、キーワード yield を使用してブロック {puts "This is a block"} を関数 MyMethod に渡しました。
上記のコードを実行すると、コンソールに以下の出力が表示されます。
This is from the method.
This is a block.
Passing the block again.
This is a block.
block と yield の違いは、block は特定のタスクを実行するためのコードの集まりであり、yield はその block を関数に渡すためのキーワードであることです。
関数が yield キーワードを取得すると、渡された block を実行してから、他の行を続行します。
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn