开发者

Rails Object#blank? vs. String#empty? confusion

Rails docs have this information for Object#blank?

An object is blank if it’s false, empty, or a whitespace string. For开发者_高级运维 example, “”, “ “, nil, [], and {} are blank.

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

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.

What am I missing in understanding how Rails' blank? method works with the empty? method of String?


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, line 66:

class String
  def blank?
    self !~ /\S/
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜