一些有效的ActiveRecord
个对象会为false
返回present?
:
object.nil? # => false
object.valid? # => true
object.present? # => false
object.blank? # => true
我更喜欢object.present?
而不是not object.nil?
。是什么决定了present?
/ blank?
的返回值?
empty?
方法,而不是blank?
或present?
方法;根据@ Simone的回答,blank?
在幕后使用empty?
。
答案 0 :(得分:7)
present?
与blank?
相反。 blank?
实现取决于对象的类型。一般来说,当值为空或类似为空时,它返回true。
你可以得到一个想法looking at the tests for the method:
BLANK = [ EmptyTrue.new, nil, false, '', ' ', " \n\t \r ", ' ', "\u00a0", [], {} ]
NOT = [ EmptyFalse.new, Object.new, true, 0, 1, 'a', [nil], { nil => 0 } ]
def test_blank
BLANK.each { |v| assert_equal true, v.blank?, "#{v.inspect} should be blank" }
NOT.each { |v| assert_equal false, v.blank?, "#{v.inspect} should not be blank" }
end
def test_present
BLANK.each { |v| assert_equal false, v.present?, "#{v.inspect} should not be present" }
NOT.each { |v| assert_equal true, v.present?, "#{v.inspect} should be present" }
end
对象可以定义自己对blank?
的解释。例如
class Foo
def initialize(value)
@value = value
end
def blank?
@value != "foo"
end
end
Foo.new("bar").blank?
# => true
Foo.new("foo").blank?
# => false
如果未指定,则会回退到最近的实施(例如Object
)。
答案 1 :(得分:1)