Ruby: assign boolean logic result to variable
Or: Why the hell?
This would be a more suitable title. Recently I ran in several potholes that took me ages to figure out. Well, usually locating the mistake in an grown code base accounts for most of the “lost time”. Replicating the issue is another factor. I often encounter issues that occur seemingly random. Some would throw huge rocks, engraved with the words ‘testing’, at various body parts of me. I like tests. I actually do tests. Well, on most parts anyway. But in this case it was in some stupid, 10 lines of code daemon-launcher.
I love making mistakes. Searching for them will force you to do several things you should’ve done while coding. I’m not talking about an missing “;” or “end”. I’m talking about some wrong behavior in certain circumstances. Code gets DRYed and refactored because nobody wants to debug complex methods. You also (re)write tests for everything involved. I often find myself writing tests for the expected behavior but don’t spend enough time to think about other cases.
I digress. Todays pothole (simplified)
a = 2 b = (a > 20 and a <= 23) or (a >=0 and a <= 4) b => false
WTF? To make this more clear:
a = 2 b = (a > 20 and a <= 23) c = (a >=0 and a <= 4) d = b or c d => false
a = 2 b = (a > 20 and a <= 23) c = (a >=0 and a <= 4) d = c or b d => true
Aha! Turns out, I did the assignment wrong. This one works as expected:
a = 2 b = (a > 20 and a <= 23) c = (a >=0 and a <= 4) d = (b or c) d => true
Apparently in this case you need the braces. No idea why though. Please enlighten me.