Empty nil

Recently I have started to add one extension to Rubys NilClass, when creating new Rails application. It is empty? method. For me is obvious that result nil.empty? should be true. Adding such method allow to write:

if some_var_which_can_be_nil.empty?
   #code to handle nil/empty case
end

Instead of

if some_var_which_can_be_nil.nil? || some_var_which_can_be_nil.empty?
   #code to handle nil/empty case
end

Using first example without extending NilClass will result with NoMethod exception, when variable will be nil:

irb(main):001:0> nil.empty?
NoMethodError: undefined method `empty?' for nil:NilClass
        from (irb):1

If in some case I would need to distinguish between nil and empty cases it can be done with check against nil in code handling nil/empty case. And of course NilClass extension is trivial:

class NilClass
  def empty?
    true
  end
end

Result? More compact and clean code, which is good ;-)

Join the Conversation

3 Comments

  1. if some_var_which_can_be_nil.blank?
    #code to handle nil/empty case
    end

    instead of

    if some_var_which_can_be_nil.nil? || some_var_which_can_be_nil.empty?
    #code to handle nil/empty case
    end

  2. One word more – nil.blank? is Rails extension to Ruby!

    In pure Ruby:

    $ irb
    irb(main):001:0> nil.blank?
    NoMethodError: undefined method `blank?' for nil:NilClass
     from (irb):1
     from :0
    irb(main):002:0>
    
    

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.