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.