Home  >  Q&A  >  body text

Ruby lamdba 相等性?

HI,以下是小弟的尝试:

p=lambda {|x| x*x}
q=p.dup
puts q==p #out false
puts p.object_id
puts q.object_id

为什么是false呢?

伊谢尔伦伊谢尔伦2759 days ago633

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-24 09:13:42

    Version problem.

    This book of yours should be relatively old, and the Ruby version you are using is before 2.0. Starting with Ruby 2.0, the behavior of Proc#== has changed:

    Starting with Ruby 2.0, Two procs are == only when they are the same object.只有当两个 proc 是同一对象时,== 才返回 true.

    Reference:

    1. https://bugs.ruby-lang.org/issues/4559

    2. https://github.com/ruby/ruby/blob/f031aec4233d7a6d4622c048abed3e86eb5dd6c2/NEWS#L127-130

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-24 09:13:42

    Looking at ruby’s official documentation, lambda is actually Proc.
    Proc does not overload its own == method, but calls BasicObject
    ’s == method

    Equality — At the Object level, == returns true only if obj and other are the same object (The method of comparing objects at the Object level is to determine whether they are the same object).
    Typically, this method is overridden in descendant classes to provide class-specific meaning.

    Proc

    Look at the base class of Proc and you can see that it inherits from Object, and then Object inherits from BasicObject

    reply
    0
  • Cancelreply