A Confusing Rubyism

The following code has the potential to be terribly confusing:

 if x = some_method monkify else rhinofy end 

In Ruby, the return value of an assignment statement is the value assigned (run a = 1 in irb and you'll see it returns 1), so this code can be understood as:

  1. Evaluate some_method and assign the value to x
  2. If the new value of x evaluates to true, run monkify
  3. If the new value of x evaluates to false, run rhinofy

Unfortunately, however, most developers are much more accustomed to seeing the equality operator == in conditionals, which means that often we'll misinterpret that code as:

  1. Evaluate some_method and compare the result to x
  2. If they are the same, run monkify
  3. If they are different, run rhinofy

In the interest of clarity, then, it's probably better to avoid using an assignment statement in a conditional. Of course, other concerns may override the need for clarity - but it's something to keep in mind.

Ben Scofield

,
Posted in Article Category: #Code
on