如何将ruby哈希数组转换为单个哈希?

时间:2014-10-25 01:07:25

标签: ruby-on-rails ruby hash

如果我从这样的哈希数组开始:

[{"name"=>"apple", "value"=>"red"},
{"name"=>"banana", "value"=>"yellow"},
{"name"=>"grape", "value"=>"purple"}]

如何将其转换为单个哈希:

{apple: "red", banana: "yellow", grape: "purple"}

有没有比做某种for循环更快的方法?

2 个答案:

答案 0 :(得分:7)

arr = [{"name"=>"apple",  "value"=>"red"},
       {"name"=>"banana", "value"=>"yellow"},
       {"name"=>"grape",  "value"=>"purple"}]

Hash[arr.map { |h| [h["name"].to_sym , h["value"]] }]
  #=> {:apple=>"red", :banana=>"yellow", :grape=>"purple"}

使用Ruby 2.1 +

arr.map { |h| [h["name"].to_sym , h["value"]] }.to_h
  #=> {:apple=>"red", :banana=>"yellow", :grape=>"purple"}

答案 1 :(得分:1)

从Splatted Array创建哈希

如果您实际上并不需要将密钥作为符号,则可以使用:

fruits = [{"name"=>"apple",  "value"=>"red"},
          {"name"=>"banana", "value"=>"yellow"},
          {"name"=>"grape",  "value"=>"purple"}]
Hash[*fruits.flat_map(&:values)]
#=> {"apple"=>"red", "banana"=>"yellow", "grape"=>"purple"}

无差异访问

如果你只想用符号而不是字符串访问元素,并且你真的不在乎键实际上会被存储为字符串,那么你可以要求一小部分ActiveSupport gem并使用HashWithIndifferentAccess

require 'active_support/core_ext/hash/indifferent_access'
fruits = [{"name"=>"apple",  "value"=>"red"},
          {"name"=>"banana", "value"=>"yellow"},
          {"name"=>"grape",  "value"=>"purple"}]
h = HashWithIndifferentAccess[*fruits.flat_map(&:values)]
h[:apple]
#=> "red"