Ruby Operators and Assignment Shortcuts

Posted by Peter Wagenet Fri, 23 Jan 2009 15:13:00 GMT

Recently I was looking through some source code (probably Rails) and discovered a handy little shortcut. When using operators, Ruby doesn’t return a true or false, it returns the actual value of the last piece that it evaluated. I’m sure most of you are familiar with using the OR operator for this. Here’s a simple example:

a = nil
b = "hello"
c = a || b # => "hello"

As you can see, the variable “c” isn’t assigned a true or false value. Instead Ruby tries to evaluate “a”, discovers that it returns nil (a false value would behave the same) and then moves on to “b” which it assigns to “c”.

What you might not have realized is that this same principle can also be applied to the AND operator.

To see how this works, take the following example:

a = "hello"
b = a ? a.length : nil #=> 5

Here we’re calling a method on “a” that won’t exist if “a” is nil. So first, we check to see if “a” exists. If it exists, we call a method on it, otherwise we return nil.

Now this works fine, but using what we’ve seen about how operators work, we can abbreviate this even more:

a = "hello"
b = a && a.length # => 5

Here, ruby first evaluates “a”, which, if it’s neither nil nor false, will then move on to check the next part: “a.length”. Since “a” isn’t nil, a.length can be called safely and returns 5. If however, “a” had been nil or false, evaluation would have stopped there and “b” would have been assigned the value of “a” (nil or false).

I admit that this isn’t a huge shortcut, but I find that it reduces a bit of redundancy in some cases and makes my code just a little bit cleaner. After all, every little bit adds up towards making nice clean code.

Comments

Leave a comment

Comments