Reputation: 325
I want to sort my ruby hash. My data comes in the following way
{"imp"=>"116", "ctr"=>"0.08", "ins"=>"7.8", "vis"=>"44"}
I'd like to prepare it the following way
{"imp"=>"116", "vis"=>"44", "ctr"=>"0.08", "ins"=>"7.8"}
what is the easiest approach to this?
Upvotes: 0
Views: 137
Reputation: 369074
Making a mapping keys to orders could be a solution:
predefined_orders = ["imp", "vis", "ctr", "ins"]
orders = Hash[predefined_orders.each_with_index.to_a]
# => {"imp"=>0, "vis"=>1, "ctr"=>2, "ins"=>3}
h = {"imp"=>"116", "ctr"=>"0.08", "ins"=>"7.8", "vis"=>"44"}
Hash[h.sort_by { |x| orders[x[0]] }]
# => {"imp"=>"116", "vis"=>"44", "ctr"=>"0.08", "ins"=>"7.8"}
h.sort_by { |x| orders[x[0]] }.to_h # Ruby 2.1+
# => {"imp"=>"116", "vis"=>"44", "ctr"=>"0.08", "ins"=>"7.8"}
h = {"imp"=>"116", "ctr"=>"0.08", "vis"=>"44"}
Hash[h.sort_by { |x| orders[x[0]] }]
# => {"imp"=>"116", "vis"=>"44", "ctr"=>"0.08"}
Upvotes: 1
Reputation: 110685
Here are two ways to do it.
h = {"imp"=>"116", "ctr"=>"0.08", "ins"=>"7.8", "vis"=>"44"}
key_order = ["imp", "vis", "ctr", "ins"]
#1
Hash[key_order.map { |k| [k, h[k]] }]
#=> {"imp"=>"116", "vis"=>"44", "ctr"=>"0.08", "ins"=>"7.8"}
or with Ruby 2.1
key_order.map { |k| [k, h[k]] }.to_h
#2
Hash[key_order.zip(h.values_at(*key_order))]
#=> {"imp"=>"116", "vis"=>"44", "ctr"=>"0.08", "ins"=>"7.8"}
Here are the steps:
a = h.values_at(*key_order)
#=> h.values_at(*["imp", "vis", "ctr", "ins"])
#=> h.values_at("imp", "vis", "ctr", "ins")
#=> ["116", "44", "0.08", "7.8"]
b = key_order.zip(a)
#=> ["imp", "vis", "ctr", "ins"].zip(["116", "44", "0.08", "7.8"])
#=> [["imp", "116"], ["vis", "44"], ["ctr", "0.08"], ["ins", "7.8"]]
Hash[b]
#=> {"imp"=>"116", "vis"=>"44", "ctr"=>"0.08", "ins"=>"7.8"}
Upvotes: 4