Reputation: 1461
I think I would see my code better if I would ask myself object.not_nil?
vs !object.nil?
. So my question: Is there really no convenience method for !nil? to sugar things up? Is it in front of my eyes and I cannot see it or am I just missing an important point?
Upvotes: 3
Views: 133
Reputation: 154603
Not that you'd necessarily want to, but you can introduce not_nil?
yourself:
class Object
def not_nil?
!self.nil?
end
end
then you can do things like:
nil.not_nil?
==> false
3.not_nil?
==> true
a = []
a.not_nil?
==> true
Upvotes: 2
Reputation: 12578
When convenience around #nil? is discussed, Activesupport's methods #blank? and #present? shouldn't be forgotten either.
Upvotes: 2
Reputation: 4991
What about this ?
if object
# sth
end
It is not the same as it will not be executed if object
is false but depending on you code, it could be better.
Another solution (which is not the same either), as you tagged your question with ruby-on-rails-3
: using present?
which will not execute the block for []
or {}
unlike !object.nil?
.
Again another one depending of the case : using unless
which won't be really nice if your condition is more complex (with &&
and/or ||
).
If your condition is of this form :
if !object.nil? && object.something?
# sth
end
You can use try
, as you are using Rails, like this :
if object.try(:something?)
# sth
end
In all the other cases, !object.nil?
or not object.nil?
stays the best solution I guess.
Upvotes: 3
Reputation: 9236
You can introduce the sugar at an upper level. Instead of:
if not object.nil?
you can write:
unless object.nil?
Upvotes: 4
Reputation: 351526
How about this?
not object.nil?
But the easier thing to do would be to check for the "truthiness" of by testing the variable itself. Since nil
is implicitly false
you can just check object
.
Upvotes: 6