Ruby Operators and Assignment Shortcuts
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.