红宝石三等分 [英] ruby triple equal

查看:49
本文介绍了红宝石三等分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码.

result = if a.is_a?(Class) && a <= Exception
   a.name
elsif ...
elsif ...
end

我将此代码重构为

case a
when Exception
     a.name
when ...
when ...
end

我是否正确理解三重相等?

Do I understand triple equal correctly?

推荐答案

我们无法从这样一个有限的例子中判断你是否真的得到 === .但是这里是当你使用 === 时真正发生的事情的分解,无论是显式还是隐式作为 case/when 语句的一部分,例如示例中使用的那个..

We can't tell whether you truly get === or not from such a limited example. But here's a break down of what's really happening when you use ===, either explicitly or implicitly as part of a case/when statement such as the one used in the example..

三重等号(===) 有许多不同的实现,这取决于左侧部分的类.它实际上只是 .=== 方法的中缀符号.这意味着以下语句是相同的:

The triple equal(===) has many different implementations that depend on the class of the left part. It's really just an infix notation for the .=== method. Meaning that the following statements are identical:

a.=== b
a === b

区别看起来并不大,但它的意思是调用左侧的 === 方法,而不是在语言级别定义的一些神奇的运算符,就像 == 但不完全一样.取而代之的是 === 在每个使用它的类中定义,可能在继承的类或 Mixin 中.

The difference doesn't look like much, but what it means is that the left hand side's === method is being invoked instead of some magical operator defined on the language level, that's like == but not quite. Instead === is defined in each class that uses it, maybe in an inherited class or Mixin.

三元等号的一般定义是,如果两个部分相同或者右边的部分包含在左边的范围内,它将返回真.

The general definition of the triple equals is that it will return true if both parts are identical or if the right part is contained within the range of the left.

在 Class.=== 的情况下,如果参数是类(或子类)的实例,则操作将返回 true.左侧为正则表达式的情况下,右侧匹配正则表达式时返回true.

In the case of Class.===, the operation will return true if the argument is an instance of the class (or subclass). In the case where the left side is a regular expression, it returns true when the right side matches the regular expression.

case of case 是一个隐含的 ===,它使用 === 将 case 变量与 when 子句进行比较,以便以下两个语句产生相同的结果.

The when of case is an implied === which compares the case variable to the when clause using === so that the following two statements produce the same result.

case a
when String
  puts "This is a String"
when (1..3)
  puts "A number between 1 and 3"
else
  puts "Unknown"
end

if String === a 
  puts "This is a String"
elsif (1..3) === a
  puts "A number between 1 and 3"
else
  puts "Unknown"
end

检查您在 === 左侧或 when 语句中使用的类型的文档,以确定事情是如何运作的.

Check the documentation for the types you use on the left hand of a === or in a when statement to be sure exactly how things work out.

这篇关于红宝石三等分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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