Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Ruby string#blank? method?

Tags:

ruby

String#blank? is very useful, but exists in Rails, not Ruby.

Is there something like it in Ruby, to replace:

str.nil? || str.empty?
like image 460
B Seven Avatar asked May 02 '13 00:05

B Seven


1 Answers

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

like image 152
aromero Avatar answered Oct 06 '22 00:10

aromero