Skip to content

Instantly share code, notes, and snippets.

@samsm
Last active November 29, 2023 17:17
Show Gist options
  • Save samsm/8224260873f70e824320def1f057f0e3 to your computer and use it in GitHub Desktop.
Save samsm/8224260873f70e824320def1f057f0e3 to your computer and use it in GitHub Desktop.
Ruby Comparable and Range!
# I was familiar with this, the keys here are "include Comparable" and the <=> method.
# <=> return 1 for larger, 0 for equal, -1 for smaller than "other"
class UndergradClassification
include Comparable
CLASSIFICATIONS = ["freshman", "sophomore", "junior", "senior"]
attr_reader :name, :index
def initialize(name)
@name = name
@index = CLASSIFICATIONS.index(name)
end
def <=>(other)
index <=> other.index
end
end
UndergradClassification.new("junior") > UndergradClassification.new("senior") # false
UndergradClassification.new("junior") < UndergradClassification.new("senior") # true
UndergradClassification.new("junior") <= UndergradClassification.new("junior") # true
# By adding succ we can support ruby Ranges!
# https://ruby-doc.org/3.2.2/Range.html
class UndergradClassification
include Comparable
CLASSIFICATIONS = ["freshman", "sophomore", "junior", "senior"]
attr_reader :name, :index
def initialize(name)
@name = name
@index = CLASSIFICATIONS.index(name)
end
def succ
next_up = CLASSIFICATIONS[index + 1]
raise RangeError.new unless next_up
self.class.new(next_up)
end
def <=>(other)
index <=> other.index
end
end
# Inclusive, two dots
(UndergradClassification.new("freshman") .. UndergradClassification.new("senior")).collect do |classification|
classification.name
end # ["freshman", "sophomore", "junior", "senior"]
# Exclusive, three dots
(UndergradClassification.new("freshman") ... UndergradClassification.new("senior")).collect do |classification|
classification.name
end # ["freshman", "sophomore", "junior"]
(UndergradClassification.new("freshman") .. UndergradClassification.new("senior")).include?(UndergradClassification.new("senior")) # true
(UndergradClassification.new("freshman") .. UndergradClassification.new("junior")).include?(UndergradClassification.new("senior")) # false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment