2012-05-04 44 views

回答

28

return語句的工作方式與其他類似編程語言的工作方式相同,只是從使用它的方法返回。 您可以跳過要返回的調用,因爲ruby中的所有方法總是返回最後一條語句。所以,你可能會發現方法是這樣的:

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-in-less-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一個例子:

# 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,我將用它來實現一個方法來查看某個數字是happy一個例子:

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不應該是'快樂嗎?(cache = [])'? –

0
def cool 
    return yield 
end 

p cool {"yes!"} 

yield關鍵字指示Ruby執行塊中的代碼。在這個例子中,塊返回字符串"yes!"。在cool()方法中使用了明確的return語句,但這也可能是隱含的。