Skip to content

Instantly share code, notes, and snippets.

@rampion
Created May 20, 2009 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rampion/114798 to your computer and use it in GitHub Desktop.
Save rampion/114798 to your computer and use it in GitHub Desktop.
simplifying definition of the comparison operator in ruby
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment