从ActiveRecord模型的集合中构建哈希 [英] Build hash from collection of ActiveRecord Models
本文介绍了从ActiveRecord模型的集合中构建哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从模型构建哈希。
I'm trying to build a hash from a Model.
这是我要构建的哈希类型。
This is the type of hash I want to build.
{"United Sates" => "us", "United Kingdom" => "uk" .....}
我已经尝试了很多方法,
I have tried so many ways now I'm just going around in circles.
这只是我一些可怜的尝试。
Here are just some of my poor attempts.
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
请提供一些建议。
谢谢
推荐答案
以下是一些单线替代方法:
Here are some one-liner alternatives:
# 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在下面的评论表示感谢:
Courtesy of @Addicted's comment below:
# Ruby 1.8+
name_to_code = countries.inject({}){ |r,c| r.merge c.name=>c.code }
这篇关于从ActiveRecord模型的集合中构建哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文