【发布时间】: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 %>
数据加载得很好,但是<%= quotation_letter_for_index(index) %> 生成的类由于被零除错误而失败。支持此功能的 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