2011-05-05 38 views
5

Rails有一个.blank?方法,如果一个Object是空的,它将返回true?或无?实际的代码可以在here找到。当我尝试在1.9.2上通过重复做这件事:复制.blank?在标准红宝石

class Object 

    def blank? 
    respond_to?(:empty?) ? empty? : !self 
    end 

end 

调用“”.blank?返回true,但调用“”.blank?根据rails documentation,空白字符串对于.blank应该为eval为true时返回false?之前,我抬头看我原本写的代码:

class Object 

    def blank? 
    !!self.empty? || !!self.nil? 
    end 

end 

并且有相同的结果。我错过了什么?

回答

12

你忘了这一点 - https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/object/blank.rb#L95

class String 
    # A string is blank if it's empty or contains whitespaces only: 
    # 
    # "".blank?     # => true 
    # " ".blank?    # => true 
    # " something here ".blank? # => false 
    # 
    def blank? 
    self !~ /\S/ 
    end 
end 
+0

+1尼斯参考'blank.rb'文件。我只是在挖掘自己... – Peter 2011-05-05 17:26:15

+0

谢谢!这就是我现在无法访问grep的原因。我会尽快将您标记为答案。 – 2011-05-05 17:27:02

0
如果他们都充满了空间只有

>> " ".empty? 
=> false 

因此

字符串,不列为empty?,你不妨也创造

class String 
    def blank? 
    strip.empty? 
    end 
end 

但仔细想想这个 - 像这样的猴子修补是危险的,特别是如果其他模块将使用您的代码。

+0

请注意未来。现在我只是学习更多关于Ruby和玩弄.blank?在IRB中。 – 2011-05-05 17:40:49

1

String类覆盖了Object实施blank? Rails中的实现:

class String 

    def blank? 
    # Blank if this String is not composed of characters other than whitespace. 
    self !~ /\S/ 
    end 

end