Ruby 复制,空白?标准红宝石
Rails有一个.blank?如果对象为空,将返回true的方法?还是零?。可以找到这方面的实际代码。当我尝试使用1.9.2时,通过执行以下操作来复制:Ruby 复制,空白?标准红宝石,ruby,Ruby,Rails有一个.blank?如果对象为空,将返回true的方法?还是零?。可以找到这方面的实际代码。当我尝试使用1.9.2时,通过执行以下操作来复制: class Object def blank? respond_to?(:empty?) ? empty? : !self end end 呼叫“空白”?返回true,但调用“”为空?当根据空格字符串的值应为true时返回false。blank?在查找我最初编写的代码之前: class Object def blan
class Object
def blank?
respond_to?(:empty?) ? empty? : !self
end
end
呼叫“空白”?返回true,但调用“”为空?当根据空格字符串的值应为true时返回false。blank?在查找我最初编写的代码之前:
class Object
def blank?
!!self.empty? || !!self.nil?
end
end
结果也一样。我错过了什么?你忘了这个-
如果字符串仅包含空格,则不会将其归类为
空?
>> " ".empty?
=> false
因此,您可能还希望创建
class String
def blank?
strip.empty?
end
end
但是请仔细考虑这一点-像这样的猴子补丁是危险的,特别是当其他模块将使用您的代码时。String类覆盖Rails实现中
blank?
的对象实现:
class String
def blank?
# Blank if this String is not composed of characters other than whitespace.
self !~ /\S/
end
end
谢谢这就是我现在无法访问grep的原因。我会尽快给你答案。我会在将来记住这一点。现在我正在学习更多关于Ruby和玩弄的知识。空白?在IRB中。
class String
def blank?
# Blank if this String is not composed of characters other than whitespace.
self !~ /\S/
end
end