未定义的方法` - '代表nil:NilClass

时间:2015-05-18 17:57:42

标签: ruby-on-rails ruby

我在Rails视图中有以下代码:

-if program.description.length > 214
          -total = 0
          -perfect_index = 0
          -program.description.split(' ').each do |word, index|
            -total += word.length
            -if total >= 214
              -perfect_index = index - 1
              -break
          =program.description.split(' ')[0..perfect_index].join(' ')
          \...
-else
  =program.description

我不知道为什么索引的值可能为nil:NilClass。我觉得问题出在我的haml变量范围内,这可能不像我认为的那样有效,但我不知道如何改善它。

2 个答案:

答案 0 :(得分:3)

仅调用each而非each_with_index会导致问题

应为program.description.split(' ').each_with_index do |word, index|

答案 1 :(得分:1)

如果您想使用索引而不是必须使用var regexp = /assets\/(\d+)/; var encodeID = regexp.exec(window.document.referrer); if (encodeID !== null && encodeID.length == 1){ $("#imageid").val(encodeID[1]); }else{ $("#imageid").val(); }

each_with_index