I'm inspecting a Rails project. On an ERuby HTML template page I saw a few lines like this:
<% option_1 = false if option_1.nil? %>
<% option_2 = false if option_2.nil? %>
<% option_3 = false if option_3.nil? %>
I can't understand why it isn't written like this:
<% option_1 ||= false %>
What's the difference of ||=
and if nil?
in this case?
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
In ruby 'a ||= b' is called "or - equal" operator. It is a short way of saying if a has a boolean value of true(if it is neither false or nil) it has the value of a. If not it has the value of b.
Well, nil is a special Ruby object used to represent an “empty” or “default” value.
Specifically, if the object responds to #empty? , they will check whether it is empty. If you go to http://api.rubyonrails.org/ and search for "blank?", you will see what objects it is defined on and how it works.
In this particular case there's no difference, but it could be out of habit. Whenever I see nil?
being used, it's almost always used inappropriately. In Ruby very few things are logically false, only literal false
and nil
are.
That means code like if (!x.nil?)
is almost always better expressed as if (x)
unless there's an expectation that x
might be literal false
.
I'd switch that to ||= false
because that has the same outcome, but it's largely a matter of preference. The only downside is that assignment will happen every time that line is run instead of once with the .nil?
test.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With