String#blank?
非常有用,但只存在于Rails框架中,而非Ruby本身。
那么在Ruby中是否有类似的函数来替代它呢?
str.nil? || str.empty?
String#blank?
非常有用,但只存在于Rails框架中,而非Ruby本身。
那么在Ruby中是否有类似的函数来替代它呢?
str.nil? || str.empty?
据我所知,纯 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?
的实现,比以前的更加高效:
strip
有点低效(特别是当你扔掉输出时)。 - Mark ThomasTrueClass
和FalseClass
分别创建补丁,因为!self
部分会自动处理它们。 - Mark Thomas您可以始终像Rails一样操作。如果您查看blank的源代码,您会发现它将以下方法添加到Object
中:
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 14
def blank?
respond_to?(:empty?) ? empty? : !self
end
respond_to?(:empty?) ? !!empty? : !self
。 - Brad Werthself !~ /\S/
来实现。不确定为什么我在这篇五年前的文章中没有注意到这一点。猜想我现在更年长更明智了 :) - Mark Thomasstr.to_s.empty?
str.to_s.strip.empty?
的意思是检查字符串是否为空或只包含空格字符。 - numbers1311407String#blank?
的提案正在 ruby-core 上进行讨论。class String
def blank?
!include?(/[^[:space:]]/)
end
end
str.nil? or str.strip.empty?
。2.0.0p0 :004 > ' '.nil? or ' '.strip.empty?
=> true
strip
可能非常低效。 - Marc-André Lafortune如果有新手需要这个,可以使用simple_ext gem。这个gem可以帮助你在Rails中使用所有Ruby核心对象的扩展,如Array、String、Hash等。
require 'simple_ext'
str.blank?
arr.blank?
... etc.
String#blank?
与测试nil?
或empty?
不等效,因为它对于仅包含空格的字符串返回true
。 - Marc-André Lafortune