Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.