Panasonic Youth

The Ruby Way, 2nd Edition, and a gotcha

This review of the The Ruby Way, Second Edition mentions one of Ruby’s fun little corners. To illustrate, what is the value of “doop” after this code?


x = true
y = false
doop = y or x

The correct answer is “false” because the “and” and “or” operators in Ruby have lower precedence then the assignment operator. There is a detailed explanation in the comments of the review, but the gist of it is this: use the standard boolean operators (&& and ||) for normal, everyday cases. Use their english counterparts when only when you really want their very low precedence to make your code cleaner.

As an aside, I’m only a few chapters in to my copy of the Ruby Way and I can tell already its going to up there with the PickAxe and Ruby for Rails, particularily for more advanced programmers. Fulton covers all sorts of fun little gotchas and corner cases found in Ruby, things that you maybe ran into once and couldn’t figure out or things that maybe you’ll never run into. So far I would say its a little bit like the classic Effective Java in how it takes a task based approach to showing the Ruby way to do things and the tradeoffs involved with different approaches.

Speaking of Effective Java, whatever happened to the talk of a second edition of it?