是什么决定了"礼物"的回归价值?

Sas*_*lla 2 ruby ruby-on-rails

一些有效的ActiveRecord对象返回falsepresent?:

object.nil? # => false
object.valid? # => true
object.present? # => false
object.blank? # => true
Run Code Online (Sandbox Code Playgroud)

我喜欢object.present?not object.nil?.什么决定了present?/ 的回报值blank?

编辑:找到了答案:我已经重新定义了empty?这个类的方法,而不是blank?present?方法; 沿着@Simone的回答,blank?正在empty?幕后使用.

Sim*_*tti 7

present?与...相反blank?.blank?实现取决于对象的类型.一般来说,当值为空或类似为空时,它返回true.

您可以查看该方法的测试:

  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
Run Code Online (Sandbox Code Playgroud)

对象可以定义自己的解释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
Run Code Online (Sandbox Code Playgroud)

如果未指定,它将回退到最接近的实现(例如Object).