iBug
iBug

Reputation: 37287

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?

Upvotes: 5

Views: 186

Answers (2)

Stefan
Stefan

Reputation: 114208

Instead of defining the missing local variables, you can use local_assigns in your views to reference local variables without causing a NameError.

So instead of:

<% option_1 ||= false %>
<% option_2 ||= false %>
<% option_3 ||= false %>

<% if option_1 %>
  ...
<% end %>

<% if option_2 %>
  ...
<% end %>

You have:

<% if local_assigns[:option_1] %>
  ...
<% end %>

<% if local_assigns[:option_2] %>
  ...
<% end %>

Upvotes: 1

tadman
tadman

Reputation: 211670

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.

Upvotes: 7

Related Questions