【问题标题】:ruby class and object - different methods of comparison [duplicate]ruby 类和对象 - 不同的比较方法
【发布时间】:2019-03-08 19:49:56
【问题描述】:

所以看下面的代码:

   s1 = "a"
=> "a"
   s1.class
=> String
   s1.class == String
=> true
   s1.class === String
=> false
   String == String
=> true
   String === String
=> false
   String === s1
=> true
   String == s1
=> false
   s1 == String
=> false
   s1 === String
=> false

我的问题是 ->

  1. 为什么String == String 评估为真,但String === String 才不是?

是不是因为事实上它们是不同的对象并且是 存储在内存的不同部分?如果是,那么我们为什么要 初始化多个 String 的 Class 对象? (不应该是那种 单身?)

String 继承自 Object 并包含 Comparable 模块。 从 Object String 获取.=== (https://ruby-doc.org/core-2.5.1/Object.html#method-i-3D-3D-3D)

从 Comparable 中得到 .== (https://ruby-doc.org/core-2.4.0/Comparable.html#method-i-3D-3D)

通过阅读定义,我发现.=== 通常与.== 相同,但字符串并非如此。我不知道为什么。

  1. 为什么s1 === String 为假而String === s1 为真?

我认为这是因为 String 的“a”对象上的 .=== 实现与 String 类上的 .=== 实现不同,但是 .=== 是如何工作的(也许它为什么在这个方式)在字符串工作(它怎么知道它应该比较对象的类而不是内存中的值/位置)?

【问题讨论】:

  • 同样的事情发生在casewhen String 不匹配,我假设case 使用===
  • 这两个算子的区别解释清楚了here.
  • 我同意,这个问题在@Kris 指出的副本中得到了解释

标签: ruby


【解决方案1】:

你是对的 ===== 是 String 类和 String 实例的不同方法。查看

的不同文档

为什么String == String 计算结果为trueString === String 没有?

正如您在文档Module.== 中看到的那样,基本上意味着双方是否是同一个对象。 String 类与String 类相同吗?是的。但如果右侧是左侧类的实例,Module.=== 将返回 true。 ID StringString 的一个实例?没有。

为什么s1 === StringfalseString === s1true

s1 === String 在字符串实例上调用===。当双方都是同一个对象时,此方法返回trueString 的实例和Sting 类是同一个对象吗?不是。但是String === s1 有——正如在is_a? 的含义之前已经解释过的那样:String 的实例是String 的实例吗?是的。

【讨论】:

  • .=== 如果右侧是该类的实例,则返回 true。我在文档中以某种方式错过了这一点。谢谢!
  • 可能值得指出的是,=== 也称为大小写相等,如Object#=== 文档中所述。当您将其作为 when 参数提供时,将调用此运算符。 case 'Hello World!'; when /ello/ then true; end #=> truecase 15; when 1..20 then true; end #=> true
  • Enumerable#grep 也使用此运算符。 [5, 25, 83, nil, 'hey'].grep(5..30) #=> [5, 25][5, 25, 83, nil, 'hey'].grep(String) #=> ['hey']
猜你喜欢
  • 1970-01-01
  • 2022-10-19
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 2017-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多