【问题标题】:Ruby helper throws zero division errorRuby 助手抛出零除法错误
【发布时间】:2016-02-23 15:19:48
【问题描述】:

我正在像这样在 rails 中循环一个数据文件 (yaml):

<% data.quotations.each_with_index do |quotation,index| %>
   <p class= "quote-<%= quotation_letter_for_index(index) %>">
     <%= quotation.quote %>
   </p>
<% end %>

数据加载得很好,但是&lt;%= quotation_letter_for_index(index) %&gt; 生成的类由于被零除错误而失败。支持此功能的 ruby​​ 助手是:

module QuotationHelpers
  QUOTATION_LETTERS = %w(a b c d e f g h)

  def quotation_letter_for_index(index)
    letter_index = QUOTATION_LETTERS.length % index
    QUOTATION_LETTERS[letter_index]
  end
end

这个想法是它会应用字母 a-h 并重复。

加载时抛出错误:ZeroDivisionError at / divided by 0

知道是什么导致了这个错误吗?这是因为初始索引值为0吗?

【问题讨论】:

  • 你是如何加载 QuotationHelpers 的?
  • 我正在使用中间人,如果放置在助手目录中,它会自动加载助手。我有许多其他助手在同一个位置工作得很好。请参阅此处的最后一行:middlemanapp.com/basics/helper_methods
  • @FabKremer 我使用了错误的助手名称。现在它加载得很好,但它会抛出一个 zerodivisionerror。有什么想法吗?
  • 是的,似乎第一次索引为零只需将此行添加到辅助方法的顶部 return QUOTATION_LETTERS[index] if index == 0

标签: ruby-on-rails ruby methods yaml helper


【解决方案1】:

你应该这样做

letter_index = index % QUOTATION_LETTERS.length

而不是

letter_index = QUOTATION_LETTERS.length % index

尝试执行QUOTATION_LETTERS.length % 0 时出现错误。

【讨论】:

  • 就是这样。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 2011-07-04
  • 2013-07-28
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多