# How to override enumerable compare for attributes?

**URL:** <https://www.ruby-forum.com/t/how-to-override-enumerable-compare-for-attributes/153744>\
**Category:** Rails\
**Created:** [November 20, 2008, 6:56pm UTC](https://www.ruby-forum.com/t/how-to-override-enumerable-compare-for-attributes/153744 "2008-11-20T18:56:31Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [November 20, 2008, 6:56pm UTC](https://www.ruby-forum.com/t/how-to-override-enumerable-compare-for-attributes/153744/1 "2008-11-20T18:56:31Z")

</div>

How would I override \<=\> for certain attributes of a class?

Say I have the following:

class Workout \< ActiveRecord::Base

# columns in db: time, weight, reps, distance

end

I want to be able to sort by results, to list workouts by best time,  
weight, etc. But the ordering is different, because a low time is  
better than a high time, while a high weight is better than a low  
weight, etc.

Right now I’m doing a class method with an if statement like this:

def self.ranked\_by(compare)  
if compare == :time  
find(:all).sort\_by{|workout| workout.time}.reverse  
else  
find(:all).sort\_by{|workout| workout.send(compare)}  
end  
end

That works, but it’s ugly and the ugliness tends to replicate itself.  
I could simplify my code by overriding the \<=\> method for the time  
attribute so that I could simply do:

def self.ranked\_by(compare)  
find(:all).sort\_by{|workout| workout.send(compare)}  
end

But how to do that?
