January 23, 2007

Ruby sort_by for Enumerables

Filed under: Technology — mmrobins @ 10:28 pm

I have been trying to figure this one out forever. I have an array of objects, usually hashes, and want to sort them. Thing is I want to sort them by their values, not their keys. Regular old sort for arrays is powerless here since it doesn’t know how to compare complex objects, let alone reach down inside them and sort by that value. I found sort_by finally, but still couldn’t get it to do what I wanted often because sometimes the objects I was sorting could have a nil value, and the sort function doesn’t know how to sort nil. Here’s an example: I have an array of Employees, and each employee has an employee_number. Actually not every employee has a number, since some are temporary. So if I try to sort by employee_number bad things happen.

Here’s how I finally made it work.

array.sort_by { |employee| employee.number.nil? : 0 : employee.number }

It basically says if the employee number is nil or null or whatever you want to call it, pretend we’re sorting by the value 0, otherwise sort by the employee number. Hooray!

1 Comment »

  1. Shouldn’t this be:

    array.sort_by { |employee| employee.number.nil? ? 0 : employee.number }

    Thanks anyway, I found this helpful.

    Comment by Zac — June 18, 2008 @ 1:54 pm

RSS feed for comments on this post. | TrackBack URI

Leave a comment

XHTML ( You can use these tags): <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> .