Is the Ruby # line empty? method?

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

Is there something similar in Ruby to replace:

 str.nil? || str.empty? 
+6
source share
5 answers

AFAIK is nothing 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 

Will this work for nil.blank? and a_string.blank? , you can extend this (e.g. rails) for true / false and shared 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 

Literature:

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

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

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

+11
source

You can always do what Rails does. If you look at the source on blank , you will see that 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 
+3
source

There is no such function in Ruby, but is there an active suggestion for String#blank? in ruby-core .

In the meantime, you can use this implementation:

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

This implementation will be very effective even for very long lines.

+2
source

Assuming your line could be deleted, what is wrong with str.nil? or str.strip.empty? str.nil? or str.strip.empty? as below:

 2.0.0p0 :004 > ' '.nil? or ' '.strip.empty? => true 
+1
source

Sort of:

str.to_s.empty?

+1
source

Source: https://habr.com/ru/post/944082/


All Articles