新手问题 为何 rails c 里面下面这个会返回 false

lyb124553153-github · 2018年07月27日 · 最后由 mingyuan0715 回复于 2018年07月31日 · 1269 次阅读

首先有个 User model

class User < ApplicationRecord
end

然后作比较的时候会发现 某条记录的 class 居然不是 User

User.first.class === User

会返回 false

User === User.first
# => true

User === User
# => false

Ruby 的 === 不是恒等,而是验证归属性的

Ruby 中的操作符都是方法,所以===不见得是恒等。

=== has absolutely nothing whatsoever to do with equality. In particular, it violates pretty much every law that you would ecpect an equality operator to follow. And it does that very much by design. – Jörg W Mittag Dec 17 '10 at 5:08 [1]

 (1..5) === 3           # => true
 (1..5) === 6           # => false

Integer === 42          # => true
Integer === 'fourtytwo' # => false

  /ell/ === 'Hello'     # => true
  /ell/ === 'Foobar'    # => false

除了上面说的 User === User.first 以外,还有 User.first.is_a? User 可以用。这里当然也可以 User.first.class == User

=== 不是判断相等的运算符。

[1]: https://stackoverflow.com/questions/4467538/what-does-the-operator-do-in-ruby

5 楼 已删除

=== 等价于 case when 中的条件判断:

condition = 'hello'
case condition
when String
when User
When (1...10)
when /ello/
end

更侧重归属感。

我觉得在 ruby 中要回答这个问题,应该是说,看这个 ===的定义

#User.first.class.method(:===).source_location
# "/Users/qinmingyuan/.rbenv/versions/2.5.1/lib/ruby/gems/2.5.0/gems/activerecord-5.2.0/lib/active_record/core.rb" 250L
# Overwrite the default class equality method to provide support for decorated models.
      def ===(object)
        object.is_a?(self)
      end

约定俗称的定义都没有源码靠谱

需要 登录 后方可回复, 如果你还没有账号请 注册新账号