Is there a Ruby string#blank? method?

AFAIK there isn't anything like this in plain Ruby. You can create your own like this:

class NilClass
  def blank?
    true
  end
end

class String
  def blank?
    self.strip.empty?
  end
end

This will work for nil.blank? and a_string.blank? you can extend this (like rails does) for true/false and general objects:

class FalseClass
  def blank?
    true
  end
end

class TrueClass
  def blank?
    false
  end
end

class Object
  def blank?
    respond_to?(:empty?) ? empty? : !self
  end
end

References:

https://github.com/rails/rails/blob/2a371368c91789a4d689d6a84eb20b238c37678a/activesupport/lib/active_support/core_ext/object/blank.rb#L57 https://github.com/rails/rails/blob/2a371368c91789a4d689d6a84eb20b238c37678a/activesupport/lib/active_support/core_ext/object/blank.rb#L67 https://github.com/rails/rails/blob/2a371368c91789a4d689d6a84eb20b238c37678a/activesupport/lib/active_support/core_ext/object/blank.rb#L14 https://github.com/rails/rails/blob/2a371368c91789a4d689d6a84eb20b238c37678a/activesupport/lib/active_support/core_ext/object/blank.rb#L47

And here is the String.blank? implementation which should be more efficient than the previous one:

https://github.com/rails/rails/blob/2a371368c91789a4d689d6a84eb20b238c37678a/activesupport/lib/active_support/core_ext/object/blank.rb#L101


You can always do exactly what Rails does. If you look at the source to blank, you see it adds the following method to Object:

# File activesupport/lib/active_support/core_ext/object/blank.rb, line 14
  def blank?
    respond_to?(:empty?) ? empty? : !self
  end

No such function exist in Ruby, but there is an active proposal for String#blank? on ruby-core.

In the meantime, you can use this implementation:

class String
  def blank?
    !include?(/[^[:space:]]/)
  end
end

This implementation will be very efficient, even for very long strings.

Tags:

Ruby