【问题标题】:Reduce method fails asking to yield block even though block given即使给出了块,Reduce 方法也无法要求产生块
【发布时间】:2018-05-30 20:08:44
【问题描述】:

我有一个包含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| 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 会导致这个问题?在调用减少之后,我正在传递一个块。我真的很想通过了解这个问题来了解如何正确使用 Enumerable 模块。

【问题讨论】:

    标签: ruby enumerable


    【解决方案1】:

    在您的each 实现中,无论是否给出块,您都调用yield,并且在each.reduce 中调用each 接收没有块

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

    def each
      return enum_for(:each) unless block_given?
      error_totals.each {|category, total| yield category, total }
    end
    

    【讨论】:

    • 我认为如果没有给出块,则会自动返回一个枚举器对象
    • 计算机科学中没有什么是自动完成的。 CPU 了解处理指令,而不是您的愿望和梦想。
    • 不正确。根据 David Black 的 The Well Grounded Rubyist 的说法,第 316 页“大多数内置迭代器在没有块的情况下被调用时会返回一个枚举器”
    • 这正是我的代码所做的。检查任何实现枚举器的开源库。
    • 我的意思是根据文档不需要检查。不是我的希望或梦想
    猜你喜欢
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多