String#blank?
is very useful, but exists in Rails, not Ruby.
Is there something like it in Ruby, to replace:
str.nil? || str.empty?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With