Fun With Ruby, Hash and ||=
A short-circuit (||=) edge case by DABlog is exactly the kind of ‘thinking about code’ that I thoroughly enjoy with Ruby. As simple an exercise as “What does this do to?”
h[:x] ||= 2
leads to an interesting exploration of the difference between || and or, what’s going on behind the scenes with ||= and ultimately made me stop and really think about the situation, though in practical terms this has never been an issue I’ve encountered. It’s just fun to walk through it in irb.
If you’re into Ruby I suggest popping over to read the article through, and do work it out in irb as you go.
Now, my two cents: if I were to read that line of code as-is in a project, I’d expect to end up with an assignment in h for key :x. The reason being:
irb(main):015:0> g NameError: undefined local variable or method `g' for main:Object from (irb):15 from :0 irb(main):016:0> g ||= 3 => 3 irb(main):017:0> g => 3
Intuitively those two ||= statements seem “same” to me.

David Black responded on 26 Mar 2008 at 4:58 am #
Hi –
I’m glad you liked the article. A flaw, as I now think, was pointed out to me; namely, that the expansion of x ||= 1 is really x || x = 1, not x or x = 1. I don’t want to be guilty of spreading wrong precedence info, so I thought I’d mention it here too
(I’ve added a comment to this effect on my blog.)
David