thoughtpunch thoughtpunch - 5 months ago 27
Ruby Question

Sort an array of hashes when some objects have nil attributes

I have an Array of hashes where the keys are User objects (it's because I'm grouping search results by user like so:

#<User:0x007ffa3d570f00> => ["taco","pizza","unicorn"]
).

I want to be able to sort the array of hashes by the User object attributes like so:

search_results.sort_by{|item| item[0].age} #item[0] = User object


However, this throws a
ArgumentError: comparison of NilClass with Integer failed
when it encounters the first user where age is Nil. I tried adding a
unless user.age.nil?
in the sort_by block, but this didn't help.

Any ideas?

Answer

Treat the nil objects as something else, perhaps 0?

search_results.sort_by { |user| user.age || 0 }

Since nil.to_i == 0, you could also do:

search_results.sort_by { |user| user.age.to_i }