2016-08-08 10 views
0

Rubyの利回りの目的は何ですか?誰かがそれを説明できましたか?収量はいくらですか?

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文を使用して、関連するブロックを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は例外を発生させます。

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 

の結果は、この情報がお役に立てば幸いなること!

関連する問題