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.
About Paul
Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.
Follow Paul on Twitter
Email: paulsturgess [at] gmail.com
Comments...
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
Just what I was looking for, thanks
Luke at 26 Jul 10 at 01:57
Very nice! I was looking for a quick and easy explanation of the ||= in Ruby and this is just what I was looking for!
Dennis at 17 Jan 11 at 11:12
also works:
@>> foo = false@
@=> false@
@>> foo = true unless defined?(foo)@
@=> false@
Ben at 23 Apr 11 at 12:49
oops actually it returns nil, not false. but foo is still false.
Ben at 23 Apr 11 at 12:50
Thanks.Very useful
soundarapandian at 25 Apr 11 at 21:03
Got something to say?