rubyruby-hash

Ruby change the order of hash keys


I have a hash and I would like the change the key order from.

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

To:

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

that can be accessed by hash["result"]["data"]. I tried;

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

But it gives error:

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


Solution

  • Try this,

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