加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 04:27:20 所属栏目:百科 来源:网络整理
导读:串#空白?非常有用,但存在于Rails中,而不是 Ruby中. 在Ruby中是否有类似的东西来代替: str.nil? || str.empty? 解决方法 AFAIK在普通的Ruby中没有这样的东西.您可以像这样创建自己的: class NilClass def blank? true endendclass String def blank? self.
串#空白?非常有用,但存在于Rails中,而不是 Ruby中.

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

str.nil? || str.empty?

解决方法

AFAIK在普通的Ruby中没有这样的东西.您可以像这样创建自己的:
class NilClass
  def blank?
    true
  end
end

class String
  def blank?
    self.strip.empty?
  end
end

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

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

参考文献:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读