Created
May 20, 2009 13:02
-
-
Save rampion/114798 to your computer and use it in GitHub Desktop.
simplifying definition of the comparison operator in ruby
This file contains 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 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