问题描述
Rails 文档 有 对象#blank?
如果对象为 false、空或空白字符串,则该对象为空.例如,"、"、nil、[] 和 {} 为空.
但是那个方法的来源是这样的:
But the source for that method is like this:
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 12
def blank?
respond_to?(:empty?) ? empty? : !self
end
现在,当我打开方便的小命令行并输入 ruby -e 'p " ".empty?'
时,它返回 false.这意味着 Rails 应该说这是一个空白值,而这显然不是.但!我打开我的 rails 控制台
并输入 " ".empty?
并像我之前的直接命令行一样得到 false.但是,我输入".blank?就像 Rails 答应我的那样,我做到了.
Now, when I open my handy little command line and type ruby -e 'p " ".empty?'
it returns false. That means that Rails should say this is a blank value when it's clearly not. But! I open my rails console
and I type " ".empty?
and get false like my earlier straight command line. But, I type " ".blank? and I get true like Rails promises me.
在理解 Rails 的 blank?
方法如何与 String 的 empty?
方法一起工作时,我缺少什么?
What am I missing in understanding how Rails' blank?
method works with the empty?
method of String?
推荐答案
Rails 在记录其 blank?
方法方面有点棘手.尽管 Object#blank?
声称也检测空格字符串,但它是通过 String#blank?
实现的,以处理空格情况和 Object#blank?
代码> 来捕捉一般情况.(空白?
也定义在其他一些类上,以节省时间.)
Rails is kinda tricky in how it documents its blank?
method. Even though Object#blank?
claims to also detect whitespace strings, it is implemented with String#blank?
to handle the whitespace case and Object#blank?
to catch the generic case. (blank?
is defined on a few other classes, too, to save time.)
activesupport/lib/active_support/core_ext/object/blank.rb,第 66 行:
class String
def blank?
self !~ /\S/
end
end
这篇关于Rails 对象#空白?与字符串#空?困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!