【问题标题】:Convert array results in ruby将数组结果转换为 ruby
【发布时间】:2015-01-07 10:05:12
【问题描述】:

如何转换以下内容

 @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']}

【问题讨论】:

  • 您想要的@results 根本不是Ruby,它应该是什么样子? @results = { 'one' => ... } 或许?

标签: ruby arrays ruby-on-rails-4 hash


【解决方案1】:

使用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"}

【讨论】:

  • @igor,顺便说一句,您希望得到一个哈希对象:{"one"=>"/new/file_one.jpg", "two"=>"/new/file_two.jpg"},而不是["one" => "/new/file_one.jpg", "two" => "/new/file_two.jpg"]。对吗?
  • OP 是否期望一个带有 => 或 {... => ...} 的数组并不重要,因为 Ruby 无论如何都会将第二个转换为第一个:['a' => 1] # => [{"a"=>1}]
  • @theTinMan,很高兴学习它。谢谢你。但它们是不同的:散列和散列数组。
  • @falsetru 是的,这就是我要找的,将编辑问题,抱歉
【解决方案2】:

只需遍历数组并提取每个子哈希的值:

[
  {"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[...] 中。

【讨论】:

    【解决方案3】:

    这是你要找的吗?

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

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 2018-06-26
      • 2015-09-14
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-17
      • 2015-05-21
      相关资源
      最近更新 更多