thoughtpunch
thoughtpunch

Reputation: 1937

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?

Upvotes: 4

Views: 4219

Answers (3)

Andrew Marshall
Andrew Marshall

Reputation: 96944

Treat the nil objects as something else, perhaps 0 or Float::INFINITY?

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 }

Upvotes: 13

Matthias Winkelmann
Matthias Winkelmann

Reputation: 16394

For boolean values, based on megas' solution:

[true, false, false, true].sort { |a|
         a ? 0 : 1
      }

=> [true, true, false, false]

Upvotes: 0

megas
megas

Reputation: 21791

Try this:

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

Upvotes: 2

Related Questions