Ruby - 如何用不同的密钥替换哈希中的密钥?

时间:2015-11-29 16:09:35

标签: ruby-on-rails arrays ruby hash

我有这个哈希:

CARS = {"Audi"     => 0, 
        "BMW"     => 1,
        ...}

来自ActiveRecord(@top_cars)的输出:

{1=>18, 0=>17, 3=>13, 5=>10, 2=>5, 4=>1}

如何使用@top_cars中的车名更换CARS的钥匙?

谢谢

修改 所以期望的输出就像{"BMW"=>18, "Audi"=>17, "Renault"=>13, "Mercedes"=>10, "Ford"=>5, "Porsche"=>1}

3 个答案:

答案 0 :(得分:2)

这样可以解决问题:

@top_cars.map {|key, value| [CARS.key(key), value]}.to_h

答案 1 :(得分:1)

可能的解决方案:

@top_cars.inject({}) {|memo, (key,value)| memo.merge(CARS.key(key) => value)}

答案 2 :(得分:1)

您可以将cars与自身合并:

cars = { "Audi"     => 0,
         "Mercedes" => 1,
         "Ford"     => 2,
         "Renault"  => 3,
         "BMW"      => 4,
         "Porsche"  => 5
       }

top_cars = {1=>18, 0=>17, 3=>13, 5=>10, 2=>5, 4=>1}

cars.merge(cars) { |*,n| top_cars[n] }
  #=> {"Audi"=>17, "Mercedes"=>18, "Ford"=>5, "Renault"=>13, "BMW"=>1, "Porsche"=>10} 

这使用Hash#merge的形式,其中使用块来确定合并的两个哈希中存在的键的值,这里是所有键。