ruby:比较两个哈希的元素

时间:2016-04-18 05:02:06

标签: ruby hash

我是红宝石的新人。我的问题:有2个哈希

首先:name =>薪水

cars = {
    "Audi" => 50000,
    "BMW" => 70000,
    "Skoda" => 30000,
    "Volvo" => 40000
}

第二名:car =>价格

result = {
    "Simon" => "BMW",
    "John" => "Audi",
    "Peter" => "Volvo",
    "Jack" => "Skoda"
}

我需要代码,结果是一个新的排序哈希" name_of_richest_man" => " the_most_expensive_car"

    .hidden 
    {
        position:absolute;
        left:-10000px;
        top:auto;
        width:1px;
        height:1px;
        overflow:hidden;
     }

2 个答案:

答案 0 :(得分:3)

people.sort_by{|_, v| v}.zip(cars.sort_by{|_, v| v})
.reverse
.map{|(k, _), (v, _)| [k, v]}.to_h
# => {"Simon"=>"BMW", "John"=>"Audi", "Peter"=>"Volvo", "Jack"=>"Skoda"}

或者,为了使其更具可读性,

[people, cars].map{|h| h.keys.sort_by{|k| h[k]}}.transpose.reverse.to_h
# => {"Simon"=>"BMW", "John"=>"Audi", "Peter"=>"Volvo", "Jack"=>"Skoda"}

答案 1 :(得分:0)

你可以写

def keys_sorted_by_decreasing_value(h)
  h.sort_by(&:last).map(&:first).reverse
end

keys_sorted_by_decreasing_value(people).zip(keys_sorted_by_decreasing_value(cars)).to_h
  #=> {"Simon"=>"BMW", "John"=>"Audi", "Peter"=>"Volvo", "Jack"=>"Skoda"}

考虑keys_sorted_by_decreasing_value中的计算:

h = people
  #=> {"Jack"=>1500, "John"=>3000, "Peter"=>2500, "Simon"=>4000} 
a = h.sort_by(&:last)
  #=> [["Jack", 1500], ["Peter", 2500], ["John", 3000], ["Simon", 4000]] 
b = a.map(&:first)
  #=> ["Jack", "Peter", "John", "Simon"] 
c = b.reverse
  #=> ["Simon", "John", "Peter", "Jack"] 

h = cars
  #=> {"Audi"=>50000, "BMW"=>70000, "Skoda"=>30000, "Volvo"=>40000} 
a = h.sort_by(&:last)
  #=> [["Skoda", 30000], ["Volvo", 40000], ["Audi", 50000], ["BMW", 70000]] 
b = a.map(&:first)
  #=> ["Skoda", "Volvo", "Audi", "BMW"] 
d = c.reverse
  #=> ["Jack", "Peter", "John", "Simon"] 

然后我们计算

e = c.zip(d)
  #=> [["Simon", "Jack"], ["John", "Peter"], ["Peter", "John"], ["Jack", "Simon"]]
e.to_h
  #=> {"Simon"=>"Jack", "John"=>"Peter", "Peter"=>"John", "Jack"=>"Simon"}