Marius Pop
Marius Pop

Reputation: 1461

Is there no convenience method for !nil?

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

Answers (5)

vacawama
vacawama

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

Boris Stitnicky
Boris Stitnicky

Reputation: 12578

When convenience around #nil? is discussed, Activesupport's methods #blank? and #present? shouldn't be forgotten either.

Upvotes: 2

tomferon
tomferon

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

Mike Aski
Mike Aski

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

Andrew Hare
Andrew Hare

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

Related Questions