Rails <% = expression%> Why no error occurs when empty

About this article

Beginner Rails articles written by beginners for beginners

I was wondering for a long time.

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.

Why doesn't the error occur?

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.

Summary

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

Rails <% = expression%> Why no error occurs when empty
[Rails] Solution when migration error occurs in acts-as-taggable-on
[No Method Error] Solution when new action occurs
Error when using rails capybara
A reminder when an aapt.exe error occurs
[Java] Why no compilation error occurs for classes that do not implement Comparable
I created a Rails post form, but I can't post it (form tag) / No error occurs
[Rails] Error resolution when generating tokens with PAYJP
Error in bundle install when running rails new
500 Internal Server Error occurs in Rails production environment
No error message is displayed when create action fails
Error encountered with notes when deploying docker on rails
[Rails] "private method` String' called ~ "error when db: migrate
What to do when a null byte error occurs
Error ExecJS :: RuntimeUnavailable: What to do when it occurs
[Android] Why a conflict version error occurs when loading some library on the Android app side
[Rails 6] What to do when a missing a template error occurs after introducing haml [Super easy]