Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 在这种情况下,收益率在做什么?_Ruby_Block - Fatal编程技术网

Ruby 在这种情况下,收益率在做什么?

Ruby 在这种情况下,收益率在做什么?,ruby,block,Ruby,Block,我正在阅读,对其中一个代码示例有疑问 在第101页,有一个例子: class VowelFinder include Enumerable def initialize(string) @string = string end def each @string.scan(/[aeiou]/) do |vowel| yield vowel end end end vf = VowelF

我正在阅读,对其中一个代码示例有疑问

在第101页,有一个例子:

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"

each
方法中,来自
scan
的每个匹配结果被传递到块,其中调用
yield
。但是,
产出元音
行到底在做什么?据我所知,
yield
用于从方法中调用块(传递给方法)。在这种情况下它在做什么?

它调用传递给方法的块,正如您所理解的。

可能值得注意的是,这是可枚举的
混合+
每个
(必须产生所需的元素)的经典用法。您只需要实现
每一个
,就可以得到所有很酷的枚举方法(在您的示例中,
inject
)。见:

可枚举的mixin为集合类提供了几个遍历和搜索方法,并具有排序功能。该类必须为每个类提供一个方法,从而生成集合的连续成员