“==="是什么意思?操作符在 Ruby 中做什么? [英] What does the "===" operator do in Ruby?

查看:29
本文介绍了“==="是什么意思?操作符在 Ruby 中做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
=== 与 Ruby 中的 ==

我最近看到它使用了几次,但无法弄清楚它的作用.谁能说明它是如何工作的?

I've seen it used a few times lately but can't figure out what it does. Can anyone illustrate how it works?

推荐答案

就像 Ruby(或实际上几乎任何面向对象的语言)中的所有其他方法一样,

Just like with every other method in Ruby (or actually pretty much any object-oriented language),

a === b

表示a类的作者想要它表示的任何内容.

means whatever the author of a's class wants it to mean.

但是,如果您不想让您的同事感到困惑,那么约定是 ===case subsumption 运算符.基本上,它是一个布尔运算符,它提出以下问题:如果我有一个标记为 a 的抽屉,将 b 放在那个抽屉中是否有意义?"

However, if you don't want to confuse the heck out of your colleagues, the convention is that === is the case subsumption operator. Basically, it's a boolean operator which asks the question "If I have a drawer labelled a would it make sense to put b in that drawer?"

另一种表述是如果 a 描述了一个集合,b 会是该集合的成员吗?"

An alternative formulation is "If a described a set, would b be a member of that set?"

例如:

 (1..5) === 3           # => true
 (1..5) === 6           # => false

Integer === 42          # => true
Integer === 'fourtytwo' # => false

  /ell/ === 'Hello'     # => true
  /ell/ === 'Foobar'    # => false

=== 运算符的主要用途是在 case 表达式中,因为

The main usage for the === operator is in case expressions, since

case foo
when bar
  baz
when quux
  flurb
else
  blarf
end

被翻译成(大致)类似的东西

gets translated to something (roughly) like

_temp = foo

if bar === _temp
  baz
elsif quux === _temp
  flurb
else
  blarf
end

请注意,如果要搜索此运算符,通常称为三等号运算符三等号运算符case 等号运算符.我真的不喜欢这些名字,因为这个运算符与相等完全没有任何关系.

Note that if you want to search for this operator, it is usually called the triple equals operator or threequals operator or case equality operator. I really dislike those names, because this operator has absolutely nothing whatsoever to do with equality.

特别是,人们会期望相等是对称的:如果 a 等于 b,那么 b 最好也等于 <代码>一个.此外,人们希望相等是可传递的:如果 a == bb == c,则 a == c.虽然在像 Ruby 这样的单分派语言中实际上无法保证这一点,但您至少应该努力保留这个属性(例如,通过遵循 coerce 协议).

In particular, one would expect equality to be symmetric: if a is equal to b, then b better be also equal to a. Also, one would expect equality to be transitive: if a == b and b == c, then a == c. While there is no way to actually guarantee that in a single-dispatch language like Ruby, you should at least make an effort to preserve this property (for example, by following the coerce protocol).

然而,对于 === 没有对称性或传递性的期望.事实上,它在很大程度上是设计对称的.这就是为什么我不喜欢称它为任何即使远程类似于平等的东西.这也是为什么我认为它应该被称为 ~~~ 之类的东西.

However, for === there is no expectation of either symmetry or transitivity. In fact, it is very much by design not symmetric. That's why I don't like calling it anything that even remotely resembles equality. It's also why I think, it should have been called something else like ~~~ or whatever.

这篇关于“==="是什么意思?操作符在 Ruby 中做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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