Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between `a ||= b` and `a = b if a.nil?

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?

like image 409
iBug Avatar asked Jun 12 '18 05:06

iBug


People also ask

How do you know if something is nil?

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).

What does ||= mean in Ruby?

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.

What does nil mean in Ruby?

Well, nil is a special Ruby object used to represent an “empty” or “default” value.

How do you check if an object is empty in Ruby?

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.


1 Answers

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.

like image 159
tadman Avatar answered Oct 05 '22 16:10

tadman