From: lpogic via ruby-core Date: 2025-02-26T14:02:54+00:00 Subject: [ruby-core:121178] [Ruby master Feature#21157] Comparison operator <> Issue #21157 has been updated by lpogic (��ukasz Pomiet��o). P3t3rU5 (Pedro Miranda) wrote in #note-3: > comparison operator already exists it's `<=>` > > if you want a class to be comparable you just include the [Comparable module](https://docs.ruby-lang.org/en/master/Comparable.html) and implement `<=>` `<=>` is good enough for comparing a single property, e.g. `a.y <=> b.y`. Things get complicated when we want to compare several consecutive properties, e.g.: ```ruby array.sort do |a, b| result = a.y <=> b.y result == 0 ? b.x <=> a.x : result end ``` Including the `Comparable` module simply moves this code to a different location. And this is only an option if we want to sort in natural order. ---------------------------------------- Feature #21157: Comparison operator <> https://bugs.ruby-lang.org/issues/21157#change-112116 * Author: lpogic (��ukasz Pomiet��o) * Status: Open ---------------------------------------- I propose introducing a comparison operator *<>* which would give the following results: ```ruby 1 <> 2 # => -1 2 <> 1 # => 1 1 <> 1 # => false 1 <> "a" # => true ``` With the help of the new operator, complex ordering expressions could be written explicitly. For example: ```ruby Point = Struct.new(:x, :y) array = [Point.new(1, 2), Point.new(6, 4), Point.new(2, 2), Point.new(5, 2)] array.sort{|a, b| a.y <> b.y || b.x <> a.x || 0 } # => [#, #, #, #] ``` The `<>` notation may look familiar to sql users, where it means 'not equal'. Defined in the form given it will retain this meaning to some extent: ```ruby a = b = 1 a_not_equal_b if a <> b a_equal_b unless a <> b ``` -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.ruby-lang.org/