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?
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With