11
A
回答
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。
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
def cool
return yield
end
p cool {"yes!"}
yield關鍵字指示Ruby執行塊中的代碼。在這個例子中,塊返回字符串"yes!"
。在cool()
方法中使用了明確的return語句,但這也可能是隱含的。
相關問題
- 1. Python收益率與Ruby收益率
- 2. 收益率回報長度
- 3. 計算回報率內部收益率
- 4. 方法採用收益率回報
- 5. 數據層收益率回報
- 6. C#收益率回報預期
- 7. 收益率回報怪異的行爲
- 8. 收益率返回無效
- 9. C#收益率返回
- 10. 在Java中的收益率返回
- 11. 如何在UML序列圖中描述C#收益率回報?
- 12. IEnumerable的<T>和「收益率回報」的性能問題
- 13. C中的收益率#
- 14. JS發電機:「收益率」與「收益率」有什麼不同?
- 15. Tornado的「收益率」與asyncio的「收益率」之間的區別?
- 16. 收益率的回報不會被調用方法的工作
- 17. 收益率回報慢的數據庫調用
- 18. 有人可以解釋爲什麼嵌套的收益率執行(C#收益率回報)嗎?
- 19. 收益率爲IList返回類型
- 20. IEnumerator收益率返回類型錯誤
- 21. 方法undefined?不能使用收益率
- 22. IEnumerable的收益率與回報相結合.AsParallel()
- 23. C#到VB .NET收益率回報轉換
- 24. 異步任務<IEnumerable>有收益率回報?
- 25. 關於收益率的回報,並從一個foreach
- 26. 紅寶石塊(收益率)
- 27. Matlab內部收益率
- 28. 收益率是多少?
- 29. 遞歸收益率(RoR)
- 30. 事件與收益率
塊的鏈接被打破 – adamscott
這是一個很好的[鏈接](http://mixandgo.com/blog/mastering-ruby-blocks-in-less-than-5-minutes) – adamscott
謝謝@adamscott,我已經改變了你的鏈接。乾杯 – Deleteman