Skip to content

Instantly share code, notes, and snippets.

@barsbek
Created March 25, 2018 09:24
Show Gist options
  • Save barsbek/42f3b59f5c1748176c46a3edf5b10b53 to your computer and use it in GitHub Desktop.
Save barsbek/42f3b59f5c1748176c46a3edf5b10b53 to your computer and use it in GitHub Desktop.
ruby: create a comparable class
class Person
include Comparable
# Comparable adds methods, which allow to compare objects
attr_reader :age
def initialize(age)
@age = age
end
def <=>(another) # method is obligatory, as Comparable uses it to construct methods
age <=> another.age
end
end
p1 = Person.new(44)
p2 = Person.new(22)
p1 > p2 # true
p1 == p2 # false
p1 < p2 # false
p3 = Person.new(33)
p3.between?(p2, p1) # true
puts [p1, p2, p3].sort.map{|p| p.inspect} # p2, p3, p1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment