Skip to content

Instantly share code, notes, and snippets.

@alagu
Created Feb 29, 2012
Embed
What would you like to do?
class SampleInherit
include Comparable
def <=>(anOther)
if anOther.respond_to? 'str' and self.respond_to? 'str'
self.str.size <=> anOther.str.size
elsif anOther.respond_to? 'num' and self.respond_to? 'num'
self.num <=> anOther.num
elsif anOther.respond_to? 'num' and self.respond_to? 'str'
self.str.size <=> anOther.num
elsif anOther.respond_to? 'str' and self.respond_to? 'num'
self.num <=> anOther.str.size
end
end
end
class SizeMatters < SampleInherit
attr :str
def initialize(str)
@str = str
end
def to_s
@str
end
end
class NumMatters < SampleInherit
attr :num
def initialize(num)
@num = num
end
def to_s
@num.to_s
end
end
s1 = SizeMatters.new("Z")
s2 = SizeMatters.new("YY")
s3 = NumMatters.new(5)
s4 = SizeMatters.new("WWWW")
s5 = SizeMatters.new("VVVVV")
s6 = NumMatters.new(2)
puts [ s3, s6, s2, s5, s4, s1 ].sort #=> [Z, YY, XXX, WWWW, VVVVV]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment