I am reading Programming Ruby 1.9 (3rd edition): The Pragmatic Programmers’ Guide, and have a question about one of the code examples.
On page 101, there is this example:
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"
In the each method, each matching result from scan is passed to the block, where yield is called. But what exactly is the yield vowel line doing? From what I understand, yield is used to call a block (that was passed to a method) from within a method. What is it doing in this situation?
It’s calling the block that’s passed to the method, just as you understand.