From: Rick DeNatale Date: 2009-05-06T22:59:33+09:00 Subject: Re: '=||' On Wed, May 6, 2009 at 9:43 AM, Eleanor McHugh wrote: > On 6 May 2009, at 13:03, Rick DeNatale wrote: >> >> The short circuiting only happens if the lhs expression returns a >> non-truthy value. >> >> Now it's true (I think) that "a op= b" is the same as "a = a op b" in >> C, Ruby ain't C. > > :) > >> Sometimes the stuff "under the hood" is a little more complicated than >> it first appears. > > > Very true, and we all learn new stuff by considering it. For example I > suspect quite a few people would be surprised by the following code: > > class Test >  def initialize >    @switch = false >  end > >  def [] x >    puts "[#{x}]" >    @switch = !@switch >  end > >  def []= x, y >    puts "[#{x}] = #{y}" >  end > end > > t = Test.new > t[:a] ||= 17 > t[:a] ||= 17 > t[:a] ||= 17 > > output:                 [a] >                                [a] >                                [a] > > here the '[]' call returns 'true' and 'false' by turns but in either event > the assignment fails to call '[]='... Are you sure? When I run your code I get this: [a] [a] [a] = 17 [a] -- Rick DeNatale Blog: http://talklikeaduck.denhaven2.com/ Twitter: http://twitter.com/RickDeNatale WWR: http://www.workingwithrails.com/person/9021-rick-denatale LinkedIn: http://www.linkedin.com/in/rickdenatale