尝试在.erb页面中截断Ruby / Sinatra中的字符串。 我一直在尝试变种:
<%= @caption_str.truncate(20) %>
<%= @caption_str[0..20] %>
但不断收到类似的错误消息:
NoMethodError at /392471267473009
undefined method `[]' for nil:NilClass
或
NoMethodError at /392471267473009
undefined method `truncate' for nil:NilClass
如果我不截断字符串,即
,一切都很好<%= @caption_str %>
我错过了什么?
答案 0 :(得分:1)
NoMethodError at /392471267473009
undefined method `[]' for nil:NilClass
或
NoMethodError at /392471267473009
undefined method `truncate' for nil:NilClass
错误足够描述。
他们传达 nil:NilClass no [] or truncate method defined
,在这种情况下证明是你的@caption_str
对象。
检查@caption_str
是否不是nil
,然后执行这些操作。如果@caption_str
nil ,您将收到相同的错误。
因为Ruby是一种动态编程语言,当值为零时,我们往往会忘记边缘情况。在出现类似情况时,请务必加检。