哈希的二维数组

时间:2014-01-08 19:08:53

标签: ruby arrays hash

在Ruby中,给定一个数组:

{"server"=>["nginx/1.1.19"], "date"=>["Wed, 08 Jan 2014 18:48:02 GMT"],"content-type"=>["application/json; charset=utf-8"]}

将此转换为哈希的最佳方法是什么:

{"server"=>"nginx/1.1.19", "date"=>"Wed, 08 Jan 2014 18:48:02 GMT","content-type"=>"application/json; charset=utf-8"}

4 个答案:

答案 0 :(得分:4)

您所拥有的是Hash而不是Array

h = {"server"=>["nginx/1.1.19"], "date"=>["Wed, 08 Jan 2014 18:48:02 GMT"],"content-type"=>["application/json; charset=utf-8"]}

Hash[h.map(&:flatten)]

# {"server"=>"nginx/1.1.19", "date"=>"Wed, 08 Jan 2014 18:48:02 GMT", "content-type"=>"application/json; charset=utf-8"}

答案 1 :(得分:3)

执行以下操作:

Hash[h.map{|k,v| [k,v[0]] }]
# => {"server"=>"nginx/1.1.19",
#     "date"=>"Wed, 08 Jan 2014 18:48:02 GMT",
#     "content-type"=>"application/json; charset=utf-8"}

答案 2 :(得分:0)

hash = {"server"=>["nginx/1.1.19"], "date"=>["Wed, 08 Jan 2014 18:48:02 GMT"],"content-type"=>["application/json; charset=utf-8"]}
hash.each{|k, v| hash[k] = v.first}
# => {"server"=>"nginx/1.1.19", "date"=>"Wed, 08 Jan 2014 18:48:02 GMT", "content-type"=>"application/json; charset=utf-8"}

答案 3 :(得分:0)

h.map do |k, v|
  if v.size > 1
    {k => v.join("; ")}
  else
    {k => v.first}
  end
end

# => [{"server"=>"nginx/1.1.19"},  {"date"=>"Wed, 08 Jan 2014 18:48:02 GMT"},  {"content-type"=>"application/json; charset=utf-8"}]

然后将其合并到一个哈希:

 h2.inject({}) do |acc, el|
   acc.merge el
 end
#=> {"server"=>"nginx/1.1.19", "date"=>"Wed, 08 Jan 2014 18:48:02 GMT", "content-type"=>"application/json; charset=utf-8"}

我假设每个值都可以是字符串数组,如果value只包含一个字符串,请转到其他更容易的答案。