Ruby module Comparable interactive
→ Click to get an interactive sample (type in code)
Methods
String
# Uses spaceship <=> operator
<'foo' < 'foo' # false Documentation
<='foo' <= 'foo' # true Documentation
=='foo' == 'foo' # true Documentation
>'foo' > 'foo' # false Documentation
>='foo' >= 'foo' # true Documentation
Numeric
# Uses spaceship <=> operator
<1 < 1 # false Documentation
<=1 <= 1 # true Documentation
==1 == 1 # true Documentation
>1 > 1 # false Documentation
>=1 >= 1 # true Documentation
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"]