Created
October 1, 2018 09:28
-
-
Save jimytc/588820a411198e6143026eb94451f46d to your computer and use it in GitHub Desktop.
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 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