From: dblack@... Date: 2006-12-24T03:55:08+09:00 Subject: Re: Help with a ruby idiom Hi -- On Sun, 24 Dec 2006, Robert Klemme wrote: > On 23.12.2006 17:02, Tim Waters wrote: >> From the O'Reilly Cookbook there is code that keeps call functions in a >> hash as a subscriber/listener type pattern. What I don't understand (or >> I don't understand how it works is the line: >> (@EventDispatcher_listeners[event] ||= []) << callback > > a ||= b > > is equivalent to > > a || (a = b) > > IOW > > a = b unless a > > IOW > > unless a > a = b > end > > IOW > > "eval b and assign the result to a if a is nil or false". It is indeed functionally equivalent to those, though all of them would blow up :-) I believe the reason a ||= b doesn't blow up is that it's expanded to: a = a || b and when Ruby sees "a =" it allocates a local variable called a -- so that means that the rhs will not raise an error, which it otherwise would. This doesn't add anything to what the idiom does, but I think it's an interesting semantic detail. David -- Q. What's a good holiday present for the serious Rails developer? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) aka The Ruby book for Rails developers! Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)