有一个Ruby字符串#black?方法?

前端之家收集整理的这篇文章主要介绍了有一个Ruby字符串#black?方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
串#空白?非常有用,但存在于Rails中,而不是 Ruby中.

Ruby中是否有类似的东西来代替:

  1. str.nil? || str.empty?

解决方法

AFAIK在普通的Ruby中没有这样的东西.您可以像这样创建自己的:
  1. class NilClass
  2. def blank?
  3. true
  4. end
  5. end
  6.  
  7. class String
  8. def blank?
  9. self.strip.empty?
  10. end
  11. end

这适用于nil.blank?和a_string.blank?你可以为真/假和一般对象扩展这个(就像rails一样):

  1. class FalseClass
  2. def blank?
  3. true
  4. end
  5. end
  6.  
  7. class TrueClass
  8. def blank?
  9. false
  10. end
  11. end
  12.  
  13. class Object
  14. def blank?
  15. respond_to?(:empty?) ? empty? : !self
  16. end
  17. end

参考文献:

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

这是String.blank?实施应该比前一个更有效:

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

猜你在找的Ruby相关文章