从ActiveRecord模型集合构建哈希

我正在尝试从模型中构建哈希。

这是我想要构建的哈希类型。

{"United Sates" => "us", "United Kingdom" => "uk" .....} 

我已经尝试了很多方法,现在我只是绕圈子走了。

这是我的一些不良尝试。

 select = Array.new countries.each do |country| # select.push({country.name => country.code }) # select[country.name][country.code] end h = {} countries.each do |c| # h[] = {c.name => c.code} # h[] ||= {} # h[][:name] = c.name # h[][:code] = c.code #h[r.grouping_id][:name] = r.name # h[r.grouping_id][:description] = r.description end 

请一些人建议。

谢谢

以下是一些单线替代方案:

 # Ruby 2.1+ name_to_code = countries.map{ |c| [c.name,c.code] }.to_h # Ruby 1.8.7+ name_to_code = Hash[ countries.map{ |c| [c.name,c.code] } ] # Ruby 1.8.6+ name_to_code = Hash[ *countries.map{ |c| [c.name,c.code] }.flatten ] # Ruby 1.9+ name_to_code = {}.tap{ |h| countries.each{ |c| h[c.name] = c.code } } # Ruby 1.9+ name_to_code = countries.to_a.each_with_object({}){ |c,h| h[c.name] = c.code } 

感谢@ Addicted的评论如下:

 # Ruby 1.8+ name_to_code = countries.inject({}){ |r,c| r.merge c.name=>c.code } 

使用Rails 4,你可以简单地做到:

 country_codes = Hash[Country.pluck(:name, :code)] 

我认为这是最优的,因为您不必加载一堆国家/地区对象并迭代它们

Rails 3上的pluck方法不允许多个属性,但您可以执行以下操作:

  country_codes = Hash[Country.connection.select_rows(Country.select('name, code').to_sql)] 

定义国家/地区哈希然后从您的记录中填写它。

 countries_hash = {} countries.each do |c| countries_hash[c.name] = c.code end 

这些天我最喜欢的答案是使用to_hto_h

 countries.pluck(:name, :code).to_h # => {"United Sates" => "us", "United Kingdom" => "uk" .....} 

扭转它们并首先获得代码

 countries.pluck(:code, :name).to_h # => {"us" => "United Sates", "uk" => "United Kingdom" .....}