Using or equals (||=) to set variables in Ruby on Rails

Posted on 27 July 2008

Using 'or equals' is great for creating and setting variables when they don't exist - useful for default values.

>>foo
=>NameError: undefined local variable or method `foo' for main:Object
>>foo ||= "bar"
=>"bar"

If variable already exists then it isn't overwritten:

>>foo = "hello"
=> "hello"
>>foo ||= "goodbye"
=>"hello"

I use this in partials sometimes where I'm expecting a local variable to be passed in but if there isn't one I'd like there to be a default.

It also means if the variable isn't passed in then you wont get an undefined error.

However, there is a gotcha you want to look out for. Observe:

>>foo = false
=> false
>>foo ||= true
=>true

The or equals actually checks if the left hand side evaluates to true and if so it isn't changed.

So the or equals is not useful for booleans. It's not difficult to work around that but it is something to keep in mind...

>> foo = false
=> false
>> foo = true if foo.nil?
=> false

Not quite as nice but it's one way to do the job.

Comments left...

  • The problem of ||= getting things wrong on falsy values got so annoying in Perl that they’ve come up with a ‘defined or’, or ‘err’ syntax. So you’d write: foo //= true and it would only change foo if foo was nil.

    Piers Cawley at 28 Jul 08 at 05:15

Got something to say?