Written by: steve ross on July 18th 2007
Often the programming pattern "set this to such-and-such unless it already has a value" pops up. It's what default parameters were invented for, but the problem is not limited to function calls. Ruby has a nifty idiom to handle this.
Here's the expanded version
if options[:title].nil? options[:title] = options[:alt] end
We could make this a bit more terse by compressing it thusly:
options[:title] = options[:alt] if options[:title].nil?
Looking better, but there's a more idiomatic way to express this:
options[:title] ||= options[:alt]
||= operator is called the "conditional assignment" operator. In fact, what's happening in the expression
lhs ||= rhs is this:
lhs = lhs || rhs
So lhs is evaluated to find out whether it produces a
true value. Remember,
nil evaluates to
false in a boolean test. If it does evaluate to
true the boolean OR short-circuit kicks in and the assignment is made (i.e., the variable
lhs remains unchanged). However, if
nil, it evaluates to
false, forcing the evaluation of
rhs and assignment of that evaluation to
Mind you, we haven't saved any machine cycles, but the next time you see
@title ||= 'myfinesite.com'
You'll know what it does!