【问题标题】:Ruby classes seem to be the same but not considered equalRuby 类似乎是相同的,但不被认为是平等的
【发布时间】:2011-10-05 11:57:24
【问题描述】:

两个对象怎么可能看起来相同但实际上并不相同?

拥有运行代码“model!(owner).send(association).should == model!(target)”的pickle_step

在标签中运行时(黄瓜 --tags @thisonescenario),所有者和目标相同并且测试通过。

当与其余场景(黄瓜)一起运行时,所有者和目标不一样。

经过检查 (rdebug) 后,代码显示这些类并不相同,即使它们看起来确实如此。黄瓜步骤的输出如下:

  expected: #<Content _id: content_1, _type: nil>
       got: #<Content _id: content_1, _type: nil> (using ==)
  Diff: (RSpec::Expectations::ExpectationNotMetError)

注意:== 被 Mongo 库重载,代码如下:

def ==(other)
  self.class == other.class &&
  attributes["_id"] == other.attributes["_id"]
end

_id 比较为真。 self.class== other.class 为假。

检查后代、祖先等类属性表明它们是相同的。

有什么想法吗?

【问题讨论】:

  • 感谢您提供的信息。这是我对堆栈溢出如何工作的误解。我已经完成并做了接受答案的事情。
  • 酷,现在self.class == other.class 应该将self.class.object_idother.class.object_id 进行比较 - 您可以在调试/测试中输出它们并查看它们是否相同?
  • 是的。这些在运行所有场景时是不同的,但在只运行一个场景时是相同的。此外,执行 self.class.ancestors 和 other.class.ancestors 显示了一个不同的模块(例如,这似乎是一些随机 id:#<0x00000105a11fe8>

标签: ruby-on-rails class comparison equality mongodb


【解决方案1】:

如果您使用 === 而不是 == 来比较类名怎么办?

类似

other === self  && ...

【讨论】:

  • 这也将匹配子类,虽然可能是可取的,但在功能上有所不同。
  • 我确实尝试过,但结果是所有对象比较都失败了。我认为 === 所做的不仅仅是比较和改变它的行为,不仅仅是因为重载,还因为语言使用(例如案例语句)。作为一个例子,你可以做 (1..5)===3 ,这是真的,这意味着 3 在 5 中。我相信 === 运算符也是 ruby​​ 中 Case 语句的基础运算符。其他示例 a = "Hello" a.class=== a => a.is_a?(a) b = "Hello" a === b 为真 a.class=== b.class 为假 => a。 class.is_a?(b.class) 但 a.class== b.class 是真的
猜你喜欢
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多