作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
目前正在解决一个试图让我将前者转变为后者的问题
{ 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}
最佳答案
看起来您正在尝试将散列拆分为键和值,分别对每个键和值进行排序,然后将它们作为散列重新组合在一起。
在这种情况下,您可以执行以下操作:
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
将按任何特定顺序生成数组,因为您无论如何都要对所有内容进行排序。
关于ruby - 有没有办法通过 sort/sort_by 更改散列的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59258467/
我是一名优秀的程序员,十分优秀!