NetManiac

Witold Rugowski on web20 wave with Ruby on Rails

Empty nil

Posted on June 16, 2007 - Filed Under Ruby, RubyOnRails

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 ;-)

Popularity: 5% [?]

Hits for this post: 2128

Similar Posts

Comments

3 Responses to “Empty nil”

  1. Robert Horvath on July 31st, 2007 10:58

    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. NetManiac on August 16th, 2007 14:21

    It is always time to learn ;))

  3. NetManiac on November 5th, 2007 0:55

    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 Reply