Trying to truncate a string in Ruby/Sinatra in an .erb page.
I have been trying variants of:
<%= @caption_str.truncate(20) %>
<%= @caption_str[0..20] %>
But keep getting error messages of the kind:
NoMethodError at /392471267473009
undefined method `[]' for nil:NilClass
or
NoMethodError at /392471267473009
undefined method `truncate' for nil:NilClass
All is well if I don’t truncate the string, i.e.
<%= @caption_str %>
What am I missing?
or
The errors are descriptive enough.
They convey that there is
no [] or truncate method definedfor nil:NilClass, which in this case turns out to be your@caption_strobject.Check if
@caption_stris notniland then do these operations. When@caption_strwould be nil, you’ll get the same error.Since, Ruby is a dynamic programming language, we tend to forget the edge-cases when the values would be nil. Always include checks when similar situations arise.