Ruby 助手抛出零除法错误

Ruby helper throws zero division error

我正在 rails 中循环访问数据文件 (yaml),如下所示:

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

数据加载正常,但 <%= quotation_letter_for_index(index) %> 生成的 class 由于被零除错误而失败。 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吗?

你应该做

letter_index = index % QUOTATION_LETTERS.length

而不是

letter_index = QUOTATION_LETTERS.length % index

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