2012-05-04 1 views

答えて

28

returnステートメントは、他の同様のプログラミング言語で動作するのと同じように機能し、使用されているメソッドから戻ってくるだけです。 ruby​​のすべてのメソッドは常に最後のステートメントを返すので、returnへの呼び出しをスキップできます。ですから、このような方法を見つけるかもしれない:

def method 
    "hey there" 
end 

実際のようなものをやってと同じです:一方

def method 
    return "hey there" 
end 

yieldを、メソッドのパラメータとして与えられたブロックをexcecutes。ですから、このような方法で持つことができます。

def method 
    puts "do somthing..." 
    yield 
end 

をし、このようにそれを使用します。

method do 
    puts "doing something" 
end 

その結果を、画面上に以下の2行印刷されます:

"do somthing..." 
"doing something" 

少しクリアしたいと思っています。ブロックの詳細については、this linkをご覧ください。

+0

ブロックへのリンクが壊れています – adamscott

+1

ここに良い[リンク](http://mixandgo.com/blog/mastering-ruby-blocks-inless-than-5-minutes) – adamscott

+0

ありがとう@adamscott、私はあなたとのリンクを変更しました。乾杯 – Deleteman

6

yieldは、メソッドに関連付けられたブロックを呼び出すために使用されます。あなたはそのような方法とそのパラメータの後にブロック(中括弧で基本的にはコード)を配置することによって、これを行う:現在の方法から

[1, 2, 3].each {|elem| puts elem} 

return終了し、戻り値としてその「引数」を使用し、そのような:

def hello 
    return :hello if some_test 
    puts "If it some_test returns false, then this message will be printed." 
end 

しかし、あなたはは、いずれの方法でreturnキーワードを使用するを持っていないことに注意してください。 Rubyは戻り値が見つからない場合、評価された最後の文を返します。したがって、これらの二つはequivelentです:

def explicit_return 
    # ... 
    return true 
end 

def implicit_return 
    # ... 
    true 
end 

はここでyieldのための例です:

私は数が happyであるかどうかを確認するためにメソッドを実装するために使用する
# A simple iterator that operates on an array 
def each_in(ary) 
    i = 0 
    until i >= ary.size 
    # Calls the block associated with this method and sends the arguments as block parameters. 
    # Automatically raises LocalJumpError if there is no block, so to make it safe, you can use block_given? 
    yield(ary[i]) 
    i += 1 
    end 
end 

# Reverses an array 
result = []  # This block is "tied" to the method 
       #       | | | 
       #       v v v 
each_in([:duck, :duck, :duck, :GOOSE]) {|elem| result.insert(0, elem)} 
result # => [:GOOSE, :duck, :duck, :duck] 

そしてreturn。たとえば、 :

class Numeric 
    # Not the real meat of the program 
    def sum_of_squares 
    (to_s.split("").collect {|s| s.to_i ** 2}).inject(0) {|sum, i| sum + i} 
    end 

    def happy?(cache=[]) 
    # If the number reaches 1, then it is happy. 
    return true if self == 1 
    # Can't be happy because we're starting to loop 
    return false if cache.include?(self) 
    # Ask the next number if it's happy, with self added to the list of seen numbers 
    # You don't actually need the return (it works without it); I just add it for symmetry 
    return sum_of_squares.happy?(cache << self) 
    end 
end 

24.happy? # => false 
19.happy? # => true 
2.happy? # => false 
1.happy? # => true 
# ... and so on ... 

:)

+0

回答ありがとうございます。 – nxhoaf

+0

ええ、問題ありません!:) – Jwosty

+0

@Jwostyは 'def happy?(cache = [])'ではないはずですか? –

0
def cool 
    return yield 
end 

p cool {"yes!"} 

yieldキーワードは、Rubyにブロック内のコードの実行を指示します。この例では、ブロックは文字列"yes!"を返します。明示的なreturnステートメントがcool()メソッドで使用されましたが、これも暗黙的であった可能性があります。

関連する問題