Lee*_*Lee 30 ruby activerecord ruby-on-rails
我正在尝试从模型中构建哈希.
这是我想要构建的哈希类型.
{"United Sates" => "us", "United Kingdom" => "uk" .....}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了很多方法,现在我只是绕圈子走了.
以下是我的一些不良尝试.
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
Run Code Online (Sandbox Code Playgroud)
请一些人建议.
谢谢
Phr*_*ogz 72
以下是一些单线替代方案:
# 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 }
Run Code Online (Sandbox Code Playgroud)
感谢@ Addicted的评论如下:
# Ruby 1.8+
name_to_code = countries.inject({}){ |r,c| r.merge c.name=>c.code }
Run Code Online (Sandbox Code Playgroud)
gui*_*eva 21
使用Rails 4,您可以简单地执行:
country_codes = Hash[Country.pluck(:name, :code)]
Run Code Online (Sandbox Code Playgroud)
我认为这是最优的,因为您不必加载一堆国家/地区对象并迭代它们
Rails 3上的pluck方法不允许多个属性,但您可以执行以下操作:
country_codes = Hash[Country.connection.select_rows(Country.select('name, code').to_sql)]
Run Code Online (Sandbox Code Playgroud)
定义国家/地区哈希然后从您的记录中填充它.
countries_hash = {}
countries.each do |c|
countries_hash[c.name] = c.code
end
Run Code Online (Sandbox Code Playgroud)
这些天我最喜欢的答案是使用pluck和to_h
countries.pluck(:name, :code).to_h
# => {"United Sates" => "us", "United Kingdom" => "uk" .....}
Run Code Online (Sandbox Code Playgroud)
反转它们并首先获得代码
countries.pluck(:code, :name).to_h
# => {"us" => "United Sates", "uk" => "United Kingdom" .....}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31696 次 |
| 最近记录: |