4

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?

4
  • 1
    Wait. If its an array of Hashes, then each element is a Hash, not a User. Hashes don't have an #age method. So I'm confused - what are you trying o accomplish? Which of the keys of each Hash do you want the #age of? Commented Apr 20, 2012 at 0:42
  • @MarkReed Hmmm, good point, though the error seems to imply that it is getting the age (since it's an integer), and otherwise it'd be failing with NoMethodError trying to call age. Commented Apr 20, 2012 at 0:46
  • Which tells me maybe your search_results isn't what you think it is. Did you try just pp'ing it? Or asking for search_results[0].class? Commented Apr 20, 2012 at 0:52
  • Maybe I didn't explain myself well enough, it's an array of hashes where the key is a 'User' object and the value is an array. Hence the "sort_by" method. This is a common pattern Commented Apr 20, 2012 at 13:08

3 Answers 3

13

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 }
Sign up to request clarification or add additional context in comments.

Comments

2

Try this:

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

Comments

0

For boolean values, based on megas' solution:

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

=> [true, true, false, false]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.