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

时间:2013-05-02 00:08:12

标签: ruby

String#blank?非常有用,但存在于Rails中,而不是Ruby。

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

str.nil? || str.empty?

6 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:3)

你总能完成Rails所做的事情。如果您查看the source to blank,就会看到它将以下方法添加到Object

# File activesupport/lib/active_support/core_ext/object/blank.rb, line 14
  def blank?
    respond_to?(:empty?) ? empty? : !self
  end

答案 2 :(得分:2)

Ruby中不存在此类功能,但ruby-core上有String#blank?的有效提案。

与此同时,您可以使用此实现:

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

即使对于非常长的字符串,此实现也非常有效。

答案 3 :(得分:1)

假设您的字符串可以被剥离,str.nil? or str.strip.empty?的错误如下所示:

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

答案 4 :(得分:1)

如下:

str.to_s.empty?

答案 5 :(得分:0)

任何新用户都可以使用simple_ext gem。这个gem帮助您从导轨上对Array,String,Hash等对象使用所有Ruby核心扩展。

require 'simple_ext'
str.blank?
arr.blank?
... etc.