Ruby 即使给定块,Reduce方法也无法请求生成块
我有一个类,我已经包括了Ruby 即使给定块,Reduce方法也无法请求生成块,ruby,enumerable,Ruby,Enumerable,我有一个类,我已经包括了可枚举模块,如下所示: class Paragraph include Enumerable attr_accessor :error_totals def initialize(text, error_totals) @original = text @error_totals = error_totals end def each error_totals.each {|category, total| yiel
可枚举
模块,如下所示:
class Paragraph
include Enumerable
attr_accessor :error_totals
def initialize(text, error_totals)
@original = text
@error_totals = error_totals
end
def each
error_totals.each {|category, total| yield category, total }
end
def totals
each.reduce(0) {|t,(category,total)| to += total }
end
end
我发现以下错误,我不明白原因:
LocalJumpError:
no block given (yield)
但是,当我执行以下操作时,它会起作用:
def total_errors_per(number_of_words:)
result = 0.0
each {|category, total| result += total.to_f/original.word_count*number_of_words}
result
end
为什么减少会导致这个问题?我正在通过一个街区后,呼吁减少。我真的很想通过理解这个问题来理解如何正确使用可枚举模块。在
每个实现中,您调用产生,无论是否给出了块,在每个中。减少调用每个都不接收块
如果未给出任何块,则应返回枚举数:
def each
return enum_for(:each) unless block_given?
error_totals.each {|category, total| yield category, total }
end
我认为,如果没有给任何块,枚举器对象将自动返回。在计算机科学中,没有什么是自动完成的。CPU理解处理指令,而不是你的愿望和梦想。不是真的。根据David Black的可靠Rubyist,pg 316“大多数内置迭代器在没有块的情况下调用时返回枚举数”,这正是我的代码所做的。检查任何实现枚举器的开源库。我的意思是根据文档不需要检查。不是我的希望或梦想