1. Computing

Convoluted Constructions: a ||= b > x


Some programmers try to fit as much logic into a single statement as possible, often using the most concise syntax available. While this often takes some clever constructions, it's usually not apparent what the code does. This type of thing is profoundly un-Ruby, and something you'll see in a language like Perl more often. However, it does show up in Ruby code from time to time.

The a ||= b > x construction is trying to do two things. First, the ||= operator will assign the result of the expression to the right of the operator to a if a is not already assigned to or is false. So if I were to say a ||= 10, the ||= operator would assign 10 to a if:

  • The variable has not yet been assigned to and is undefined.

  • The variable is false, or holds a value that evaluates to false such as nil.

The second part of this statement, b > x, is not often seen outside of conditional statements. The operator is straightforward, and will evaluate to either true or false. In this case, the result will be assigned to a variable instead of used in a conditional statement. Other than this it's no different than a conditional statement.

So, put together, this convoluted construction does the following: If the variable a is undefined or false, assign the true/false value of the comparison operator to the variable a. So what's a better way to say this?

 #!/usr/bin/env ruby
 unless a
   a = b > x
 # Or even just this
 a = b > x unless a

Those two solutions are longer, but they're much easier to read. Easier to read is almost always better than shorter.

  1. About.com
  2. Computing
  3. Ruby
  4. Advanced Ruby
  5. Convoluted Constructions
  6. Convoluted Constructions: a = b > x

©2014 About.com. All rights reserved.