Reputation: 45943
String#blank?
is very useful, but exists in Rails, not Ruby.
Is there something like it in Ruby, to replace:
str.nil? || str.empty?
Upvotes: 12
Views: 9660
Reputation: 805
Anyone new looking for this, can use simple_ext gem. This gem helps you to use all the Ruby core extensions on objects like Array, String, Hash etc. from rails.
require 'simple_ext'
str.blank?
arr.blank?
... etc.
Upvotes: 1
Reputation: 25761
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:
Upvotes: 17
Reputation: 79562
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.
Upvotes: 2
Reputation: 37517
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
Upvotes: 4
Reputation: 34677
Assuming your string can be stripped, what's wrong with str.nil? or str.strip.empty?
as in the following:
2.0.0p0 :004 > ' '.nil? or ' '.strip.empty?
=> true
Upvotes: 2