【发布时间】: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
我的问题是 ->
- 为什么
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)
通过阅读定义,我发现.=== 通常与.== 相同,但字符串并非如此。我不知道为什么。
- 为什么
s1 === String为假而String === s1为真?
我认为这是因为 String 的“a”对象上的 .=== 实现与 String 类上的 .=== 实现不同,但是 .=== 是如何工作的(也许它为什么在这个方式)在字符串工作(它怎么知道它应该比较对象的类而不是内存中的值/位置)?
【问题讨论】:
-
同样的事情发生在
case,when String不匹配,我假设case使用===。 -
这两个算子的区别解释清楚了here.
-
我同意,这个问题在@Kris 指出的副本中得到了解释
标签: ruby