From: Jacob Fugal Date: 2006-05-10T02:18:30+09:00 Subject: Re: code snippet: can it be done better/shorter? On 5/9/06, Robert Dober wrote: > On 5/9/06, Jacob Fugal wrote: > > An expression of the form 'a || b' is equivalent to this: > > > > a ? a : b > Which is unfortunately not true because of possible side effects, in > our case however there are none and it was a *nice way* to explain > things, but watch out for method calls. True. I should have said "essentially equivalent". :) For those unclear what Robert means here, consider this contrived code: $ cat > test.rb $a_called = false def a if $a_called puts "Called again." return false else puts "Called once." $a_called = true return true end end x = a ? a : "default" puts "x is #{x.inspect}." $a_called = false x = a || "default" puts "x is #{x.inspect}." x = a || "default" puts "x is #{x.inspect}." $ ruby test.rb Called once. Called again. x is false. Called once. x is true. Called again. x is "default". Using the ternary form, the method a gets called multiple times; using the || form, it only gets called once and the value from that call is reused. So a || b is more closely equivalent to: (tmp = a) ? tmp : b But this is nowhere near as nice looking, and may still be not *quite* there. :) Jacob Fugal