From: Phillip Gawlowski Date: 2008-05-02T06:10:48+09:00 Subject: Re: Please explain nuances of ||= -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 David A. Black wrote: |> x ||= y expands into x = x || y, since x == 1 expands to x = x + 1, and | | I think you mean +=. Yes, indeed. |> we have no reason to expect ||= to behave differently (MPLOS). | | That's really where this thread always starts, though: why doesn't it | behave like x = x || y in every case? Anyway, the thing about MPOLS is | that you and I can't invoke it :-) It was actually Matz who showed me | the x || x = y expansion (most recently at EuRuKo, where I talked to | him about it because I wanted to make sure the corrections I made to | my blog post had made it correct). It doesn't behave that way because classes can implement and override behavior. Which can lead to surprising results, and sometimes pathological cases of Monkeypatching. ;) Also, the MPLOS helps as a guideline, not as a hard and fast rule. :) |> And Robert's answer works the way it works because the Hash has a |> default value set, which doesn't equate to false or nil. If you override |> the default value by setting the value to false, the assignment works |> again as expected. | | Right, but hashes are allowed to have default values. So an | explanation that accounts for that case is better than one that | doesn't. The point is that if you do a drop-in replacement x = x || y | you get a different result from ||=, and with x || x = y you don't. | That means, definitively I think, that the latter is a more correct | expansion. (I'm not sure how it couldn't mean that.) However, a default value results in the Hash not evaluating to nil or false. Which is required for || and OR to use their *second* operand (since it otherwise uses the first operand), so x || x = y cannot work. Unless we get into precedence issues here, I guess. | Anyway, this is at least the third thread on this in recent months, | and I've written my blog post (and correction follow-up :-) about it. | I think I'm about ||='d out. So am I. - -- Phillip Gawlowski Twitter: twitter.com/cynicalryan Blog: http://justarubyist.blogspot.com ~ Why do we drink cow's milk? Who was the first guy who first looked at a cow and said "I think I'll drink whatever comes out of these things when I squeeze 'em!"? -- Calvin -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.8 (MingW32) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iEYEARECAAYFAkgaMdsACgkQbtAgaoJTgL+7ggCfZvH1Zt26JJtfKA+uPdd28oPV /28AnjWINp8XwuVrx00X2qRT/LCtz/Ny =CldW -----END PGP SIGNATURE-----