我不能夠理解這個代碼的邏輯:「每個」和「注入(符號)」方法如何在下面的代碼中工作?
class VowelFinder
include Enumerable
def initialize(string)
@string = string
end
def each
@string.scan(/[aeiou]/) do |vowel|
yield vowel
end
end
end
vf = VowelFinder.new("the quick brown fox jumped")
vf.inject(:+) # => "euiooue"
如何對象
vf.inject(:+)
調用該程序的方法each
?each
方法在這個程序中如何工作,因爲在函數定義中沒有提到塊參數?如果我只是打電話
vf.each
,爲什麼我會收到以下錯誤?vowel_finder.rb:8:in `block in each': no block given (yield) (LocalJumpError) from vowel_finder.rb:8:in `scan' from vowel_finder.rb:8:in `each' from vowel_finder.rb:13:in `<main>'
之一幾件事情,我理解的是,在這個類的each
方法覆蓋從包含Enumerable
模塊each
方法。除此之外,我不明白任何關於each
和塊。
有人可以請解釋我的邏輯和它是如何工作的內部?
可能重複的[在Ruby中的塊和產量](http://stackoverflow.com/questions/3066703/blocks-and-yields-in-ruby) –
可能會通過文章[在Ruby中構建枚舉和枚舉器](https://www.practicingruby.com/articles/building-enumerable-and-enumerator)會讓事情變得清晰 –