0

I've been recently allocated to a new Rails project in which I could see assignments to variables are made using ||= instead of =. Can any one help me understand if this is a correct way or a good practice in Rails and the advantages/disadvantages of using it?

e.g.

a ||= b + c

(b and c are integers)

Thanks for any help :)

Stefan
  • 109,145
  • 14
  • 143
  • 218
Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85
  • Are you aware that `a ||= b` means `a = a || b`, nothing more, nothing less? It's not a question of whether `a ||= b` or `a = b` is "better"; they serve completely different purposes. It's a little like asking whether one should use `+` or `-`. Perhaps your question should just concern the use of `||=`. – Cary Swoveland Dec 12 '14 at 04:59
  • @CarySwoveland: While I agree with the main thrust of your comment, as paxdiablo shows, `a ||= b` is not actually `a = a || b`. – Amadan Dec 12 '14 at 05:08
  • Did you see paxdiablo's answer? `a ||= b` is not `a = a || b`, but it is `a || a = b`. Excuse me, I'm not that thorough with ruby.. – Rajesh Omanakuttan Dec 12 '14 at 05:09
  • Good point, @Amadan. Thanks. I'll remember that. I see I omitted `+ c` as well. – Cary Swoveland Dec 12 '14 at 05:21

1 Answers1

4

With:

a = b + c

a gets set to the sum of b and c no matter what.

With:

a ||= b + c

it only gets set to the sum if it's currently set to nil or false.

It's a subtle difference but one that Ruby bods should learn. People coming from C-like languages often see a ||= x as:

a = a || x

but that's not actually the case. Instead, it's:

a || a = x

(no assignment is actually done if a is already set to a non-nil/false value).

Ruby Inside goes into some more depth on the matter here.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • 1
    Also, one advantage to using this syntax that should be mentioned is that if 'a' (in this example) has already been defined (and is truthy) then the 'x' part won't be evaluated, which can be handy if it's expensive. – jbeck Dec 12 '14 at 05:09