在Ruby中实现平等性

Ruby is one of the few programming languages that get equality right. I often play around with other languages, but keep coming back to Ruby. This is largely because Ruby’s implementation of equality is so nice.

Ruby是为数不多的能够正确处理平等问题的编程语言之一。我经常玩其他语言,但总是回到Ruby。这主要是因为Ruby对平等的实现是如此的好。

Nonetheless, equality in Ruby isn't straightforward. There is #==, #eql?, #equal?, #===, and more. Even if you’re familiar with how to use them, implementing them can be a whole other story.

尽管如此,Ruby中的平等并不简单。有#==,#eql?,#equal?,#===,等等。即使你熟悉如何使用它们,实现它们也是一个完全不同的故事。

Let's walk through all forms of equality in Ruby and how to implement them.

让我们来看看Ruby中所有形式的平等以及如何实现它们。

Why Properly Implementing Equality Matters

为什么正确实施平等很重要

We check whether objects are equal all the time. Sometimes we do this explicitly, sometimes implicitly. Here are some examples:

我们一直在检查对象是否相等。有时我们明确地这样做,有时隐含地这样做。下面是一些例子。

  • Do these two Employees work in the same Team? Or, in code: denis.team == someone.team.
  • 这两个Employees ,是否在同一个Team ?或者,在代码中。denis.team == someone.team.
  • Is the given DiscountCode valid for this particular Product? Or, in code: product.discount_codes.include?(given_discount_code).
  • 给定的DiscountCode ,对这个特定的Product ,是否有效?或者,在代码中。product.discount_codes.include?(given_discount_code).
  • Who are the (distinct) managers for this given group of employees? Or, in code: employees.map(&:manager).uniq.
  • 谁是这组雇员的(不同的)经理?或者,用代码表示。employees.map(&:manager).uniq.

A good implementation of equality is predictable; it aligns with our understanding of equality.

对平等的良好实施是可以预测的;它与我们对平等的理解相一致。

An incorrect implementation of equality, on the other hand, conflicts with what we commonly assume to be true. Here is an example of what happens with such an incorrect implementation:

另一方面,平等的不正确实现与我们通常认为的真实情况相冲突。下面是一个例子,说明这种不正确的实现会发生什么。

The geb and geb_also objects should definitely be equal. The fact that the code says they’re not is bound to cause bugs down the line. Luckily, we can implement equality ourselves and avoid this class of bugs.

gebgeb_also 对象肯定应该是相等的。事实上,代码中说它们不相等,必然会导致下一步的错误。幸运...

开通本站会员,查看完整译文。

ホーム - Wiki
Copyright © 2011-2024 iteam. Current version is 2.134.0. UTC+08:00, 2024-09-28 10:17
浙ICP备14020137号-1 $お客様$