L
Lowell Kirsh
I have a class called foo and I want to make it comparable so that I can
sort arrays of Foo. Here is the class:
class Foo
attr_accessor :a, :b, :c, :d
def <=>(rhs); (see below); end
end
I'm assuming that the a,b,c, and d field are each Comparable. To compare
2 Foos, we first look at the a's and if they're not the same, we return
the result of their comparison. If they are the same, we continue to
compare the b's, and if they're the same we compare the c's, and so on
until we compare the last field. So for my definition of <=> I have the
following, which works, but I'd like something better/shorter:
if (@a <=> rhs.a) != 0
@a <=> rhs
elsif (@b <=> rhs.b) != 0
@b <=> rhs.b
elsif ....
Is there a more concise way of doing this? I know this code isn't the
ugliest, but something in my gut tells me there's got to be a better
way. Especially if we have more than 4 variables.
lowell
sort arrays of Foo. Here is the class:
class Foo
attr_accessor :a, :b, :c, :d
def <=>(rhs); (see below); end
end
I'm assuming that the a,b,c, and d field are each Comparable. To compare
2 Foos, we first look at the a's and if they're not the same, we return
the result of their comparison. If they are the same, we continue to
compare the b's, and if they're the same we compare the c's, and so on
until we compare the last field. So for my definition of <=> I have the
following, which works, but I'd like something better/shorter:
if (@a <=> rhs.a) != 0
@a <=> rhs
elsif (@b <=> rhs.b) != 0
@b <=> rhs.b
elsif ....
Is there a more concise way of doing this? I know this code isn't the
ugliest, but something in my gut tells me there's got to be a better
way. Especially if we have more than 4 variables.
lowell