通过红宝石哈希数组迭代 [英] iterate through array of hashes in ruby
问题描述
所以,如果我有像这样的哈希值的数组:(红宝石初学者)
so if I have an array of hashes like so: (ruby beginner)
input = [
{"last_name"=>"Gay", "first_name"=>"Rudy", "display_name"=>"Rudy Gay", "position"=>"SF", "minutes"=>39, "points"=>25, "assists"=>6},
{"last_name"=>"Collison", "first_name"=>"Darren", "display_name"=>"Darren Collison", "position"=>"PG", "minutes"=>39, "points"=>14, "assists"=>4}
]
如何将我通过遍历数组以及通过散列每个迭代有这样的事情:
how would i iterate through the array as well as to iterate through each hash to have something like this:
PLAYER1 = {DISPLAY_NAME =>盖伊,位置=>SF}
player1 = {display_name=>"rudy gay", "position"=>"SF"}
player2 = {DISPLAY_NAME =>达伦 - 科里森,位置=>PG}
player2 = {display_name=>"darren collison", "position"=>"PG"}
它会是这样的。
input.each do |x|
Player.create(name: x['display_name'], position: x['position']
end
(假设我有一个球员模型)
(assuming I have a player model)
有没有更好的方式来实现这一目标?
Is there a better way to achieve this?
谢谢!
推荐答案
鉴于你输入:
input = [
{ "last_name"=>"Gay", ... },
{ "last_name"=>"Collison", ...}
]
如果所有这些钥匙(姓氏,FIRST_NAME,DISPLAY_NAME)都在播放器
模型$ P $ psent,你可以:
If all of those keys (last_name, first_name, display_name) are present in the Player
model, you can just:
input.each do |x|
Player.create(x)
end
由于创建
将属性分配的哈希值。但是,甚至更好,你甚至都不需要遍历:
Since create
will take a hash of attributes to assign. But, even better, you don't even need to iterate:
Player.create(input)
ActiveRecord的将通过所有这些,如果你给它哈希值的数组。
ActiveRecord will go through them all if you give it an array of hashes.
这篇关于通过红宝石哈希数组迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!