Dealing with nil in your enumerable while using sort_by

If you're ever using sort_by in Ruby to sort something Enumerable and want to handle nil values consider the following.

Let's say you have an array that looks like [1,4,2,nil,9]. Calling sort_by like this [1,4,2,nil,9].sort_by { |num| num } will result in an ArgumentError since you're implicitly comparing a Fixnum value with nil.

A good way to get around this is to assign a default value to any nil values. You can do that within the block like this: [1,4,2,nil,9].sort_by { |num| num || (num.send(:==,!nil) || 0) }

If num is nil, then return the result of comparing num to !nil or 0. Since num is nil, nil != nil, so 0 is returned.

It took me writing this to see how overkill/redundant that is, and yet that's what I first settled on. The easiest way to do this is of course [1,4,2,nil,9].sort_by { |n| n || 0 }

The situation I was dealing with was actually an array of objects. Let's say you had the following array of hashes: [{ :name => "Zack", :age => 23} , { :name => "Steven", :age => 28 } , { :name => "Michelle", :age => 26 } ]

You could sort the "people" in that array (call it 'users') by their ages like this: sorted_users = users.sort_by { |u| u[:age] }

If there's a possibility that an age could be nil, you could default that person's age to 0 (or something else) just like we did above: users.sort_by { |u| u[:age] || 0 }

...hmm. I was going somewhere with this and had an example using send but now I don't remember and I need to go.