Matthew Clark
Matthew Clark

Reputation: 1965

Ruby: sort array of hashes, even though key may not exist

In a rails application, I have an array of hashes which I can sort easily with just

array_of_hashes.sort_by { |hash| hash[:key_to_sort] }

But what if not every array member has a key :key_to_sort? Then the sort will fail "comparison of String with nil failed". Is there a way to allow the sort to continue? Or is there another way to do this?

Upvotes: 9

Views: 2566

Answers (1)

Lukas Stejskal
Lukas Stejskal

Reputation: 2562

It depends what you want to do when a hash doesn't have sorting key. I can imagine two scenarios:

1) exclude the hash from sorting

arr.delete_if { |h| h[:key_to_sort].nil? }.sort_by { |h| h[:key_to_sort] }

2) place the hash at the beginning/end of the array:

arr.sort_by { |h| h[:key_to_sort] || REALLY_SMALL_OR_LARGE_VALUE }

Upvotes: 13

Related Questions