From: Phillip Gawlowski Date: 2008-05-02T05:24:47+09:00 Subject: Re: Please explain nuances of ||= -----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" [0] http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/297145 - -- Phillip Gawlowski Twitter: twitter.com/cynicalryan Blog: http://justarubyist.blogspot.com ~ Calvin: I'm a genius, but I'm a misunderstood genius. Hobbes: What's misunderstood about you? Calvin: Nobody thinks I'm a genius. -- Calvin -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkgaJxMACgkQbtAgaoJTgL8e0QCdHbW1PniEGPZSlC9Api4lIL7u viAAnis9nThp0JAXQEwGWU+JEM5s+ssL =3HqG -----END PGP SIGNATURE-----