public
Last active

simplifying definition of the comparison operator in ruby

  • Download Gist
compare_by.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
class Object
def self.compare_by(*methods)
include Comparable
define_method('<=>') do |other|
methods.inject(0) do |_,method|
comp = self.send(method) <=> other.send(method)
break comp if comp != 0
comp
end
end
end
end
 
class T
def initialize(name,f1, f2)
@name,@f1, @f2 = name,f1, f2;
end
 
def f1
puts "checking #@name's f1"
@f1
end
def f2
puts "checking #@name's f2"
@f2
end
 
compare_by :f1, :f2
end
 
x = T.new('x',1,2)
y = T.new('y',2,3)
z = T.new('z',2,4)
 
p x < y #=> checking x's f1
# checking y's f1
# true
p x < z #=> checking x's f1
# checking z's f1
# true
p y > z #=> checking y's f1
# checking z's f1
# checking y's f2
# checking z's f2
# false

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.