ブロックを暗黙の引数として呼び出すことができます。このメソッドの内部では、yieldキーワードと値を使用してブロックを呼び出すことができます。 メソッドは、Rubyのyield文を使用して、関連するブロックを1回以上呼び出すことができます。したがって、パラメータはいつでもブロックを実行するために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
が呼び出された場合、Rubyは例外を発生させます。
ドキュメントをお読みになりましたか? –