Reputation: 34053
I have this code conditionally displaying the project's title if we're in a view that has the @project
instance variable:
<title>My app <%= "- " + @project.title if @project.present? %></title>
But it gives me an error with the following message: "can't convert nil into String", i.e. it tries to execute my string concatenation despite the conditional statement being false.
Why does it even bother?
Upvotes: 0
Views: 39
Reputation: 176472
You check if a project is present
@project.present?
but you don't check if the value of its title
property is set. When title
is nil
, the following concatenation
"- " + @project.title
will fail with the can't convert nil into String
error because you are effectively trying to concatenate
"- " + nil
that are two different types. You must deal with this case explicitly or use nil-to-string casting by using the interpolation
<%= "- #{@project.title}" if @project.present? %>
Moreover, beware of precedences. Embedding if conditions in that way with a print, may lead to obscure bugs caused by evaluation precedence.
Upvotes: 2