用ruby转换数组结果



如何转换以下

 @results = [{"id"=>"one", "url"=>"/new/file_one.jpg"}, 
             {"id"=>"two", "url"=>"/new/file_two.jpg"}]

 @results = {"one" => "/new/file_one.jpg", 
             "two" => "/new/file_two.jpg"}

我应该使用"地图"还是"收集"?以..开头。。

@results.map{ |x| x['id']}

使用Hash::[]:

@results = [{"id"=>"one", "url"=>"/new/file_one.jpg"},
             {"id"=>"two", "url"=>"/new/file_two.jpg"}]
Hash[@results.map { |x| [x['id'], x['url']] }]
# => {"one"=>"/new/file_one.jpg", "two"=>"/new/file_two.jpg"}

在Ruby 2.1+中,您还可以使用Enumerable#to_h:

@results.map { |x| [x['id'], x['url']] }.to_h
# => {"one"=>"/new/file_one.jpg", "two"=>"/new/file_two.jpg"}

只需迭代数组并提取每个子哈希的值:

[
  {"id"=>"one", "url"=>"/new/file_one.jpg"},
  {"id"=>"two", "url"=>"/new/file_two.jpg"}
].map(&:values).to_h 
# => {"one"=>"/new/file_one.jpg", "two"=>"/new/file_two.jpg"}

如果您的Ruby不支持to_h,那么将其全部封装在Hash[...]中。

这就是您想要的吗?

results.map{ |x| {x['id'] => x['url']} }

最新更新