Chautauqua Logo

Ruby module Comparable interactive

Prompt icon → Click to get an interactive sample (type in code)

Methods

String

# Uses spaceship <=> operator
<=>'a'<=>'b'; 'a'<=>'a'; 'b'<=>'a' # -1;0;1 Documentation Interactive samplePlayground
-1
 
<'foo' < 'foo' # false Documentation
<='foo' <= 'foo' # true Documentation
=='foo' == 'foo' # true Documentation
>'foo' > 'foo' # false Documentation
>='foo' >= 'foo' # true Documentation
between?'c'.between?('a','d') # true Documentation Interactive samplePlayground
true
clamp'd'.clamp('a'..'f'); 'z'.clamp(…) # d;f Documentation Interactive samplePlayground
f

 

Numeric

# Uses spaceship <=> operator
<=>1<=>2; 1<=>1; 2<=>1 # -1;0;1 Documentation Interactive samplePlayground
-1
 
<1 < 1 # false Documentation
<=1 <= 1 # true Documentation
==1 == 1 # true Documentation
>1 > 1 # false Documentation
>=1 >= 1 # true Documentation
between?3.between?(1,5) # true Documentation Interactive samplePlayground
true
clamp7.clamp(0,50); 70.clamp(0,50) # 7;50 Documentation Interactive samplePlayground
7

Your own class

class Version
  include Comparable
  attr_reader :major, :minor

  def initialize(major, minor) = (@major, @minor = major, minor)

  # Define <=> once ...
  def <=>(other) = [major, minor] <=> [other.major, other.minor]

  def to_s = "#{major}.#{minor}"
end

v1_2  = Version.new(1, 2)
v1_10 = Version.new(1, 10)

# ... and get < <= == > >= between? clamp for free
v1_2 < v1_10                              # => true ('1.2' < '1.10' is false)
v1_2 == Version.new(1, 2)                 # => true
Version.new(2, 0).between?(v1_2, v1_10)   # => false
Version.new(9, 9).clamp(v1_2, v1_10).to_s # => "1.10"
[v1_10, v1_2].sort.map(&:to_s)            # => ["1.2", "1.10"]