Skip to content

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.

View the snippets archive ››

1 comment made

Piers Cawley commented on 28 Jul 08 at 05:15

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.

Got something to say?

About

Paul is a Rails developer for Kyan web agency.

Checkout his ramblings about music, what he's listening to and his other random thoughts.

He also writes on the Kyan blog.

More snippets

Take a look in the archive

Need a website?

Your best bet is to contact Paul's employer. Make sure to check out the portfolio of work.

Hosting

I recommend hostingrails.com

Contact

my name at gmail.com