I've been using Ruby for a while now, and I keep seeing this:
foo ||= bar
What is it?
I've been using Ruby for a while now, and I keep seeing this:
foo ||= bar
What is it?
This will assign bar
to foo
if (and only if) foo
is nil
or false
.
EDIT: or false, thanks @mopoke.
Operator ||= is a shorthand form of the expression:
x = x || "default"
Operator ||= can be shorthand for code like:
x = "(some fallback value)" if x.nil?
From: http://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Operators
If you're using it for an instance variable, you may want to avoid it. That's because
@foo ||= bar
Can raise a warning if @foo
was previously uninitialized. You may want to use
@foo = bar unless defined?(@foo)
or
@foo = bar unless (defined?(@foo) and @foo)
depending on whether you want to merely check if @foo is initialized, or check if @foo has truthiness (ie isn't nil
or false
).