From: "David A. Black" Date: 2008-05-02T05:42:29+09:00 Subject: Re: Please explain nuances of ||= HI -- On Fri, 2 May 2008, Phillip Gawlowski wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Robert Klemme wrote: > | On 01.05.2008 20:54, Simon Krahnke wrote: > |> * David A. Black (18:56) schrieb: > |> > |>> Hi -- > |>> > |>> On Fri, 2 May 2008, Ruby Freak wrote: > |>> > |>>> I am reading some of the ruby files in rails and I an seeing the ||= > |>>> method used a lot. > |>>> knowing ruby the way I do, I realize that she has lots of magical > |>>> surprises and I really want to get to know this girl! > |>> x ||= y means: x || x = y > |> > |> No, it means: x = x || y > | > | I believe you are wrong. > | > | irb(main):001:0> h={} > | => {} > | irb(main):002:0> h=Hash.new true > | => {} > | irb(main):003:0> h[1] > | => true > | irb(main):004:0> h[1] ||= 10 > | => true > | irb(main):005:0> h > | => {} > | irb(main):006:0> > | > | If you were right, h would look differently: > | > | irb(main):008:0> h=Hash.new true > | => {} > | irb(main):009:0> h[1] = h[1] || 10 > | => true > | irb(main):010:0> h > | => {1=>true} > | > | The same topic has been discussed exhaustively a few days ago. > | > | Cheers > | > | robert > | > | > > You are wrong, too, though. > > I refer you to Ruby-Talk 297145[0]: > > Quoth Joshua Ballanco: > 'The only reason that Chris' example behaves like "x || x = stuff" is > because he's defined a default value for the hash. If you set a default > value, than you'll never have a keyed value be empty (i.e. nil). ' > > x = x || 'a value' works when x is nil or false. Once the Hash has a > default value, it shouldn't be false, much less nil. > > See: > > irb(main):001:0> h = Hash.new > => {} > irb(main):002:0> h[1].nil? > => true > irb(main):003:0> h[1] = h[1] || 10 > => 10 > irb(main):004:0> h[2] = 'not nil' > => "not nil" > irb(main):005:0> h[2] = h[2] || 'a value' > => "not nil" > irb(main):006:0> h[3] = false > => false > irb(main):007:0> h[3] = h[3] || 'not false' > => "not false" The question, though, is what x ||= y expands to. Robert's point is that if you say it expands to x = x || y, that doesn't account for what happens with a hash that has a non-false default value. Mind you, x || x = y doesn't account (as I mentioned) for the fact that if x isn't defined, you can't use that syntax. x ||= y is really its own thing, and doesn't expand 100% of the time to anything. But x || x = y, if you allow for the undefined x thing, describes all of the behaviors, including the hash edge case. David -- Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates!