A Confusing Rubyism
Ben Scofield, Former Viget
Article Category:
Posted on
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:
- Evaluate
some_method
and assign the value tox
- If the new value of
x
evaluates to true, runmonkify
- If the new value of
x
evaluates to false, runrhinofy
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:
- Evaluate
some_method
and compare the result tox
- If they are the same, run
monkify
- 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.