1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rubyの比較演算子の挙動を変えたいなら、<=>をオーバーライドすべし

Last updated at Posted at 2021-06-26

結論は、「比較演算子(<, ==, >)ではなく、<=>を再定義すべし」。

当初の疑問

><==の整合性ってどうやって取るんだっけ?

答え

def <=>(other) ~~(javaでいうObject#compareTo)~~を再定義する。他の>, <, ==は触らない。
from: https://stackoverflow.com/a/13973761

def ==(other)の実装は、return True if self<=>other == 0 else Falseのようになっている。
(https://docs.ruby-lang.org/ja/latest/class/Comparable.html)

考察

なぜこんがらがったのかを考えてみた。Javaだと、

  • 比較演算子(==, <, >)の挙動を書き換えることはできない。
  • equalsToとcompareToを書き換えても、これによって比較演算子(==, <, >)の結果が変わることはない。(確かsortingの並び順は変わるはずだ)

一方rubyだと、

  • 比較演算子(==, <, >)の挙動を書き換えることはできる。
  • また、<=>を書き換えることによっても、比較演算子の挙動が変わる。
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?