简体   繁体   English

根据数组中相同键的顺序对哈希键进行排序

[英]Sort Hash Keys based on order of same keys in array

I need to sort an Hash according to order of keys present in other array: 我需要根据其他数组中的键的顺序对Hash进行排序:

hash = { a: 23, b: 12 }
array = [:b, :a]
required_hash #=> { b: 12, a: 23 } 

Is there any way to do it in single line? 有没有办法在单行中做到这一点?

hash = { a: 23, b: 12 }
array = [:b, :a]

array.zip(hash.values_at(*array)).to_h
  #=> {:b=>12, :a=>23}

The steps: 步骤:

v = hash.values_at(*array)
  #=> [12, 23]
a = array.zip(v) 
  #=> [[:b, 12], [[:a, 23]]
a.to_h
  #=> {:b=>12, :a=>23}

You can try something like this: 你可以尝试这样的事情:

array = [:b, :a] 
{ a: 23, b: 12 }.sort_by { |k, _| array.index(k) }.to_h
#=> {:b=>12, :a=>23}

If 如果

hash = { a:23, b:12 }
array = [:b, :a]

As a one liner: 作为一个班轮:

Hash[array.map{|e| [e, hash[e]]}]

As for ordering, it was some time ago, when ruby changed the implementation where the hash keys are ordered according to insert order. 至于排序,它是在不久前,当ruby改变了根据插入顺序排序哈希键的实现。 (Before that there was no guarantee that keys would be sorted one way or another). (在此之前,无法保证密钥会以某种方式排序)。

I do not see any sorting, I think essentially you are doing this: 我没有看到任何排序,我认为你基本上是这样做的:

hash = { a:23, b:12 }
array = [:b, :a]
res = {}
array.each { |key| res[key] = hash[key] } && res # `&& res` is just syntax sugar to return result in single line
#=> {:b=>12, :a=>23}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM