Created
March 25, 2018 09:24
-
-
Save barsbek/42f3b59f5c1748176c46a3edf5b10b53 to your computer and use it in GitHub Desktop.
ruby: create a comparable class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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