Ruby: Nil or empty

Are you frustrated when checking for an empty value in Ruby, and always end up having to check for nil too? Have you gladly moved from PHP to Ruby but long for some flexibility in variable typing? Just include nil_or_empty.rb below:

module NilOrEmpty
  module AlwaysTrue
    def nil_or_empty?
      true
    end
  end

  module CheckEmpty
    def nil_or_empty?
      empty?
    end
  end
end

class Array
  include NilOrEmpty::CheckEmpty
end

class Hash
  include NilOrEmpty::CheckEmpty
end

class NilClass
  include NilOrEmpty::AlwaysTrue
end

class String
  include NilOrEmpty::CheckEmpty
end

Instead of calling nil? or empty? on a variable, call nil_or_empty? to check if the value is nil or empty, like an array without values, a hash without keys, or a string with no characters.

Adding such methods may be considered as polluting core classes, but then creating new classes by inheriting from core ones may be overkill, in my opinion. This is only meant to ease many cases when you have to check for both nil and an empty value.

If you work on a Rails project, or anything else using the ActiveSupport gem, you already have the #blank? method doing the same thing than above. As I often work on Ruby code not built with Rails, this slipped my mind. (Thanks to @keita on App.net for reminding me of this.)

Leave a Reply