Skip to content

Instantly share code, notes, and snippets.

@jimytc
Created October 1, 2018 09:28
Show Gist options
  • Save jimytc/588820a411198e6143026eb94451f46d to your computer and use it in GitHub Desktop.
Save jimytc/588820a411198e6143026eb94451f46d to your computer and use it in GitHub Desktop.
class Pen
include Comparable
attr :serialNumber, :length
def initialize(serialNumber, length)
@serialNumber = serialNumber
@length = length
end
def to_s
"SN: #{serialNumber}, length: #{length}"
end
def <=>(other)
if length > other.length
1
elsif length < other.length
-1
else
0
end
end
def ==(other)
return true if object_id == other.object_id
return false unless other.is_a?(Pen)
return serialNumber == other.serialNumber
end
end
pensInMyPocket = []
pensInMyPocket << Pen.new("a", 10)
pensInMyPocket << Pen.new("a", 4)
pensInMyPocket << Pen.new("b", 15)
pensInMyPocket << Pen.new("c", 7)
pensInMyPocket << Pen.new("b", 1)
puts "Before sort by length:"
pensInMyPocket.each { |pen| puts "\t#{pen}" }
puts "After sort by length:"
pensInMyPocket.sort.each { |pen| puts "\t#{pen}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment