即使给出了块,Reduce方法也无法要求产生块

问题描述 投票:1回答:1

我有一个类,我已经包括Enumerable模块如下:

class Paragraph
  include Enumberable
  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

为什么减少导致这个问题?我在调用reduce之后传递了一个块。我真的想了解如何通过理解这个问题正确使用Enumberable模块。

ruby enumerable
1个回答
1
投票

在你的each实现中,无论是否给出块,你都会调用yield,并且在each.reduce中调用each不会被阻塞。

如果没有给出阻止,则应该返回一个枚举器:

def each
  return enum_for(:each) unless block_given?
  error_totals.each {|category, total| yield category, total }
end
© www.soinside.com 2019 - 2024. All rights reserved.