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
2) place the hash at the beginning/end of the array: