=== 与 Ruby 中的 == [英] === vs. == in Ruby

查看:31
本文介绍了=== 与 Ruby 中的 ==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,== 和 === 有什么区别?RDoc

In Ruby, what is the difference between == and ===? The RDoc says

大小写相等——对于类 Object,实际上与调用 #== 相同,但通常被覆盖提供有意义的后代case 语句中的语义.

Case Equality—For class Object, effectively the same as calling #==, but typically overridden by descendents to provide meaningful semantics in case statements.

#==== 一样吗?您能否举例说明在 case 语句中何时/如何使用?

Is #== the same as ==? And could you provide an example of when/how this is used in case statements?

推荐答案

这两者真的没什么关系.特别是,#== 是相等运算符,而 #==== 与相等完全无关.就我个人而言,我发现 #=== 看起来与 #== 如此相似,使用等号并且通常被称为 case 相等运算符, triple equals operatorthreequals operator 当它真的与相等无关时.

The two really have nothing to do with each other. In particular, #== is the equality operator and #=== has absolutely nothing to with equality. Personally, I find it rather unfortunate that #=== looks so similar to #==, uses the equals sign and is often called the case equality operator, triple equals operator or threequals operator when it really has nothing to do with equality.

我将 #=== 称为 case 包含运算符(这是我能想到的最好的方法,我愿意接受建议,尤其是来自以英语为母语的人的建议).

I call #=== the case subsumption operator (it's the best I could come up with, I'm open to suggestions, especially from native English speakers).

描述 a === b 的最佳方式是如果我有一个标有 a 的抽屉,把 b> 在里面吗?"

The best way to describe a === b is "if I have a drawer labeled a, does it make sense to put b in it?"

例如,Module#=== 测试是否b.is_a?(a).如果您有 Integer === 2,将 2 放在标记为 Integer 的框中是否有意义?是的,它确实.Integer === 'hello' 怎么样?显然不是.

So, for example, Module#=== tests whether b.is_a?(a). If you have Integer === 2, does it make sense to put 2 in a box labeled Integer? Yes, it does. What about Integer === 'hello'? Obviously not.

另一个例子是Regexp#===.它测试匹配.将 'hello' 放在标记为 /el+/ 的框中是否有意义?是的,确实如此.

Another example is Regexp#===. It tests for a match. Does it make sense to put 'hello' in a box labeled /el+/? Yes, it does.

对于诸如范围之类的集合,Range#=== 被定义为成员资格测试:如果该元素在集合中,则将元素放入标有集合的框中是有意义的.

For collections such as ranges, Range#=== is defined as a membership test: it makes sense to put an element in a box labeled with a collection if that element is in the collection.

所以,这就是 #=== 所做的:它测试参数是否可以包含在接收器下.

So, that's what #=== does: it tests whether the argument can be subsumed under the receiver.

这与 case 表达式有什么关系?简单:

What does that have to with case expressions? Simple:

case foo
when bar
  baz
end

if bar === foo
  baz
end

这篇关于=== 与 Ruby 中的 ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆