This post originated from an RSS feed registered with Ruby Buzz
by Jay Fields.
Original Post: Ruby: Multiple ifs (unless)
Feed Title: Jay Fields Thoughts
Feed URL: http://blog.jayfields.com/rss.xml
Feed Description: Thoughts on Software Development
I recently ran into some code similar to the snippet below.
item.currency if item.currency !=:usdunless item.nil?
Based on reading the code I assumed it worked as expected; however, having never actually tried it myself I decided to hit irb for a moment with the following code.
p 3unless p 2unless p 1
Sure, I'm not using if, but if and unless have the same precedence, so I thought the example was good enough.
p 3unless p 2unless p 1 # >> 1 # >> 2 # >> 3
The output shows the execution order: The rightmost if (or unless) is evaluated first and then it moves to the next conditional immediately to it's left.
Of course, the statement could be rewritten simply using ||.