首页 > 解决方案 > 有没有办法通过 sort / sort_by 更改哈希的键?

问题描述

目前正在解决一个试图让我将前者转变为后者的问题

{ a: 2, b: 5, c: 1 } => { a: 1, b: 2, c: 5 }

试图做到这一点

hash = { a: 2, b: 5, c: 1 }.sort_by {|k,v| v}.to_h

这给出了这个 =>{:c=>1, :a=>2, :b=>5}

如何在对值进行排序时更改哈希的键?

标签: ruby

解决方案


看起来您正在尝试将散列拆分为键和值,分别对它们进行排序,然后将它们作为散列重新组合在一起。

在这种情况下,您可以执行以下操作:

hash.to_a.transpose.map(&:sort).transpose.to_h

一步一步,它的工作原理是这样的:

# First array-ify the hash into key/value pairs
hash.to_a
# [[:a, 2], [:b, 5], [:c, 1]] 

# Then transpose to group the keys and values together
hash.to_a.transpose
# [[:a, :b, :c], [2, 5, 1]]

# Then sort the keys and values separately
hash.to_a.transpose.map(&:sort)
# [[:a, :b, :c], [1, 2, 5]] 

# And transpose again to get key/value pairs
hash.to_a.transpose.map(&:sort).transpose
# [[:a, 1], [:b, 2], [:c, 5]] 

# And combine the array of key/value pairs into a hash
hash.to_a.transpose.map(&:sort).transpose.to_h
# {:a=>1, :b=>2, :c=>5} 

您也可以手动执行如下hash.to_a.transpose步骤:

[hash.keys, hash.values].map(&:sort).transpose.to_h

您甚至不必假设#keys并且#values会以任何特定顺序生成数组,因为无论如何您都在对所有内容进行排序。


推荐阅读