我试图理解这四种方法之间的区别。我知道默认情况下==调用方法等于?当两个操作数都指向同一个对象时返回true。

===默认也调用==哪个调用equal?…如果这三个方法都没有被覆盖,那么我猜 ===, == and equal?做完全一样的事情?

现在是eql?。这是做什么(默认情况下)?它是否调用操作数的哈希/id?

为什么Ruby有这么多等号?它们应该在语义上有所不同吗?


当前回答

=== #——大小写相等

== #——一般相等

两者的工作原理类似,但“===”甚至可以执行case语句

"test" == "test"  #=> true
"test" === "test" #=> true

区别就在这里

String === "test"   #=> true
String == "test"  #=> false

其他回答

=== #——大小写相等

== #——一般相等

两者的工作原理类似,但“===”甚至可以执行case语句

"test" == "test"  #=> true
"test" === "test" #=> true

区别就在这里

String === "test"   #=> true
String == "test"  #=> false

我想扩展一下===运算符。

===不是相等运算符!

Not.

让我们把这一点讲清楚。

在Javascript和PHP中,===可能是一个相等操作符,但在Ruby中,这不是一个相等操作符,并且具有根本不同的语义。

那么===是做什么的呢?

===是模式匹配操作符!

===匹配正则表达式 ===检查范围成员关系 ===检查是否是类的实例 ===调用lambda表达式 ===有时可以检查是否相等,但大多数情况下不能

那么,这种疯狂是怎么说得通的呢?

可枚举#grep在内部使用=== 语句内部使用===的情况 有趣的是,救援在内部使用===

这就是为什么在语句中可以使用正则表达式、类和范围,甚至lambda表达式。

一些例子

case value
when /regexp/
  # value matches this regexp
when 4..10
  # value is in range
when MyClass
  # value is an instance of class
when ->(value) { ... }
  # lambda expression returns true
when a, b, c, d
  # value matches one of a through d with `===`
when *array
  # value matches an element in array with `===`
when x
  # values is equal to x unless x is one of the above
end

所有这些示例都可以使用pattern === value以及grep方法。

arr = ['the', 'quick', 'brown', 'fox', 1, 1, 2, 3, 5, 8, 13]
arr.grep(/[qx]/)                                                                                                                            
# => ["quick", "fox"]
arr.grep(4..10)
# => [5, 8]
arr.grep(String)
# => ["the", "quick", "brown", "fox"]
arr.grep(1)
# => [1, 1]

我编写了一个简单的测试。

def eq(a, b)
  puts "#{[a, '==',  b]} : #{a == b}"
  puts "#{[a, '===', b]} : #{a === b}"
  puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
  puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end

eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)

.eql吗?—如果接收方和实参具有相同类型且值相等,则此操作符返回true。

例如- 10.eql?(10.0)为假值。

=== -它将在case语句中测试是否相等。

例如-(1…10)=== 1为真

== -该操作符检查两个给定的操作数是否相等。如果等于,则返回TRUE,否则返回FALSE。

例如-(1…10)== 1为假

更多示例请点击这里

Ruby公开了处理相等的几种不同方法:

a.equal?(b) # object identity - a and b refer to the same object

a.eql?(b) # object equivalence - a and b have the same value

a == b # object equivalence - a and b have the same value with type conversion.

点击下面的链接继续阅读,它给了我一个清晰的总结理解。

https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/equality-matchers

希望它能帮助别人。