← Back to Upcase

Code style: If variable vs if variable?


(Javier Holguera) #1

I’m new to Ruby and I was surprised when I found out that all objects are true apart from nil and false. Even 0 is true.

A nice thing about that property of the language is that you can write:

if !variable

do stuff when variable is nil

end

My colleagues, who are more seasoned Ruby developers, insist I should choose that instead of using .nil? like so:

if variable.nil?

do stuff when variable is nil

end

However I believe that the latter is a better option for two reasons: 1. I think it’s more object oriented, especially in a language like Ruby where everything is an object and message exchange. 2. It is more readable, in my subject opinion, even if it is less compact.

Am I making a “newbie” mistake here?

Thanks for the help!


(Catherine Cai) #2

Did you ask them for their rationale?

Honestly, I feel like it’s a matter of personal choice. I tend to go with the much less favored “unless variable”.


(Frank West) #3

Another option would be to write it as:

if variable == nil
  # do stuff when variable is nil
end

The difference between this and variable.nil? is a stylistic one, but I have been on teams that prefer one over the other.

What happens when you set variable = false ? In the first instance the code block that is only supposed to be executed when it is nil gets executed anyways. That is not the expected behavior of the code as described. In the .nil? or == nil instances, you won’t run into the same problem. Is that a problem? Who knows, but it definitely can be and I have seen it happen more than once.

**As a small note, Sandi made me write variable == nil in her exercises in her class. Trying to remember her reasoning.