2014-02-19 113 views
-1

我有一个像这样的对象数组:(我知道这是丑陋的)红宝石乐趣循环

[ 
    { :application_type => 
     #<OrgSpecific::ApplicationType _id: 4cd2c13f8ed7df3230000002, 
     org_parameters: { "CENTER_LOCATION" => [["Not Applicable"]], 
          "LEVELX" => [["Graduate"]], 
          "LOCATION" => [["Online"], ["University Campus"]] 
          }, 
     comment: "MSW", 
     hide_deadline: false, 
     payable_on_submission: true, 
     name: "Graduate">, 
    :requirement=>"available" 
    }, 
    # (imagine more of these) 
] 

我想创建通过这个数组循环的方法,并应用类型ID作为返回一个对象属性和值要求属性中的值如下:

{"4cd2c13f8ed7df3230000002" => "available", "4cd2c13f8ed7df3230000003" => "available"} 

但我对地图,lambdas,proc没有经验。有什么简单的方法来做到这一点?我知道红宝石,我可能只用几行就可以做到。任何帮助,将不胜感激!

+1

如果你要以代码的形式提出你的问题,如果代码是可执行的,它将更容易回答。 – diedthreetimes

回答

0

不是最优雅的解决方案,但很简单。

your_array = [{:application_type =>"type", :requirement=>"available"}] 

result_hash = {} 
your_array.each{|x| res[x[:application_type]] = x[:requirement]} 


puts result_hash #=> {"type"=>"available"} 

当然,在你的榜样,你需要像x[:application_type].id

编辑: 如果你正在寻找一个班轮你也可以做到以下几点:

  1. 使用注入以跟踪结果散列给你。

    your_array.inject({}){|i, x| i[x[:application_type]] = x[:requirement]; i}

  2. 使用收集到返回一组[键,值]对,然后转换成散列

    Hash[your_array.collect{|x| [x[:application_type], x[:requirement]]}]

选项[2]可能是最可读。

+0

那就是我最后的结局。这不太好,但谢谢你! – MoDiggity

+0

看我的编辑。我认为这两种选择都是优越的,第二种选择使得代码的意图更加明显。 (将散列数组转换为单个散列) – diedthreetimes