Ruby:从Hash创建哈希=>组

时间:2009-11-14 21:23:10

标签: ruby arrays hash set

我有一个联接表,我用它来查找订单表单的可用服务;该表格中包含utility_idcompany_id

我想要的是一个组(哈希),其中键是实用程序名称,值是相应公司的哈希值。

我得到了以下内容......

Service.find(:all).to_set.classify { |service| Utility.find(service.utility_id).name }

...非常好地给了我一个散列,其中键是实用程序名称,但值是设置的服务记录,而不仅仅是公司名称(我不需要)实际的记录),我无法弄清楚我是如何制作我想要的哈希:

# example of what I would like to have
{"electricity" => {"conEd" => 1, "Dominian" => 2}, "gas" => {"conEd" => 1}} 
# where the key is Utility.name, and the value-hash is {Company.name => Company.id}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

find(:all)向我建议Rails,所以假设您在Utility和Service模型之间有正确的HABTM,这个代码段适用于我的测试环境:

results = Hash.new
Utility.find(:all).each do |utility|
  results[utility.name] = Hash.new
  utility.companies.each do |company|
    results[utility.name][company.name] = company.id
  end
end
results

哪个产生

{"Communications"=>{"InternetCo"=>2, "PhoneCo"=>1}, "Energy"=>{"ElectricCo"=>4, "GasCo"=>3, "OilCo"=>5}}