Beginner Rails articles written by beginners for beginners
I intended to put some value in the instance variable with controller, but in fact it was empty (nil) and it was a mystery that no error occurred even if I passed that variable to view.
The reason is that when ** <% = expression%>
is output, the to_s method
is called for the expression **.
That is, the resulting output is always automatically <% = expression.to_s%>
. The reason why this method can be used is that all Ruby objects have a to_s method
.
When you call the to_s method
on an empty instance (nil.to_s
), ** an empty string is output **. I don't get an error, and nothing is displayed as it is.
#controller
@name = nil
#view
<p><%= @name.to_s %>Mr.</p>
#output
#=>Mr.
It's hard to notice when I've just learned because there are no errors, but it seems easier to discover what kind of problem is occurring when I understand that "this is what happens behind the scenes". From then on, I thought again that I would continue to study properly.
Recommended Posts