Random Rubyisms That I Keep Forgetting

I haven’t been blogging because I thought that I hadn’t really solved any problems recently worth writing about. However, I forgot that I just recently came across a few Rubyisms that I had totally missed (or learned and forgotten). Here are a few bits that were enlightening to me:

  • if x && y: If x is nil, then y doesn’t run. I’ve had a few double if statements in my code previously because I forgot that the second part of the statement won’t even run if the first is nil/false.
  • x = if y then b else c end: assigned x = b if y is true, else c. I knew the inline x = b if y, but didn’t quite realize that you could do the full if else. NOTE: this is kept on one line for the sake of bullets. If you were really writing it, you would want to split it out into separate lines, with the first line being x = if y.
  • case statement when/then: Assuming you know what a full normal case statement looks like (if not, here’s a nice little post), have you seen them written as when/then? For example: when x then :is_x. To me that is much more easy to read than a when x (new line) :is_x. Definitely a personal preference though :)

That’s all for now. But I also have some Python/Ruby differences that I’ve found intriguing recently.