Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 289
Matthew Clark Avatar asked Sep 27 '11 13:09

Matthew Clark


1 Answers

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 }
like image 65
Lukas Stejskal Avatar answered Nov 09 '22 02:11

Lukas Stejskal