From: Robert Klemme Date: 2006-12-24T19:00:06+09:00 Subject: Re: Help with a ruby idiom On 23.12.2006 19:55, dblack@wobblini.net wrote: > 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. Absolutely! I had this slightly nagging feeling that I had the first variant wrong, and indeed $ ruby -e 'a || (a=1); p a' -e:1: undefined local variable or method `a' for main:Object (NameError) Thanks for the correction! robert