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.