ben
ben

Reputation: 29777

What is yield doing in this situation?

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?

Upvotes: 0

Views: 100

Answers (2)

tokland
tokland

Reputation: 67850

It may be worth noting that this is a classical usage of a Enumerable mix-in + each (which must yield the desired elements). You just need to implement each and you get all the cool methods (in your example, inject) of enumerables. See:

http://www.ruby-doc.org/core/classes/Enumerable.html

"The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection."

Upvotes: 0

Chuck
Chuck

Reputation: 237010

It's calling the block that's passed to the method, just as you understand.

Upvotes: 1

Related Questions