Ruby 更改哈希键的顺序

Ruby change the order of hash keys

我有一个散列,我想更改密钥顺序。

{"result"=>{"data"=>[{"Quantity"=>13, "Rate"=>17.1},
                    {"Quantity"=>29,"Rate"=>3.2}, 
                    {"Quantity"=>7, "Rate"=>3.4}]}}

收件人:

{"result"=>{"data"=>[{"Rate"=>17.1, "Quantity"=>13}, 
                    {"Rate"=>3.2, "Quantity"=>29}, 
                    {"Rate"=>3.4, "Quantity"=>7}]}}

可以通过 hash["result"]["data"] 访问。我试过了;

hash["result"]["data"][0].each_value{|v| v.replace({"Rate" => v.delete("Rate")}.merge(v))}

但它给出了错误:

NoMethodError (undefined method `delete' for 17.1:Float):

试试这个,

hash["result"]["data"].each{|v| v.replace({"Rate" => v.delete("Rate")}.merge(v))}

我觉得他们没必要做这么多手术。我想 data 包含您的整个哈希,然后只需一张映射和哈希的反向即可解决您的问题。

data['result']['data'] = data['result']['data'].map{|v|  Hash[v.to_a.reverse]}

还有四种方法...

颠倒那些哈希项的顺序:

hash['result']['data'].map! { |h| h.to_a.reverse.to_h }

将"Quantity"移动到最后:

hash['result']['data'].each { |h| h["Quantity"] = h.delete("Quantity") }

将第一项移到末尾:

hash['result']['data'].map! { |h| h.merge([h.shift].to_h) }

强制执行特定的给定顺序:

keys = ["Rate", "Quantity"]
hash['result']['data'].map! { |h| keys.zip(h.values_at(*keys)).to_h }