=== 不是一个平等运算符!
不.
但是,它是什么?
您可能熟悉===Javascript和PHP中的相等运算符,但这不是Ruby中的相等运算符,并且与其他语言具有根本不同的语义.
那怎么===办?
=== 是模式匹配运算符!
=== 匹配正则表达式=== 检查范围成员资格=== 检查是一个类的实例 === 调用lambda表达式=== 有时检查平等,但大多数情况下都没有那么这种疯狂是如何有意义的呢?
Enumerable#grep在===内部使用case when语句在===内部使用这就是为什么你可以在case when语句中使用正则表达式和类和范围甚至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
# value matches one of a, b, c 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
Run Code Online (Sandbox Code Playgroud)
所有这些示例pattern === value也适用于grep方法.
我只能猜测为什么没有!==方法,但Tadman的直觉似乎发现上,===主要是通过使用间接case when和grep,因此可能似乎并不需要一个明确的逆操作.大多数生产代码的样式指南都禁止使用===操作员.
如果您正在寻找其他相等运算符,请检查.eql?和.equal?