Ruby:排序哈希数组,即使密钥可能不存在

时间:2021-05-10 16:01:16

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

在rails应用程序中,我有一个哈希数组,我可以轻松地排序

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?

但是,如果不是每个数组成员都有一个键:key_to_sort?然后排序将失败“String与nil的比较失败”。有没有办法让排序继续下去?或者还有另一种方法吗?

1 个解决方案

#1


12  

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

1)从排序中排除哈希

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:

2)将哈希放在数组的开头/结尾:

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

#1


12  

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

1)从排序中排除哈希

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:

2)将哈希放在数组的开头/结尾:

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