迭代ruby中的哈希数组

时间:2021-10-06 14:30:19

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=>"rudy gay", "position"=>"SF"}

player1 = {display_name =>“rudy gay”,“position”=>“SF”}

player2 = {display_name=>"darren collison", "position"=>"PG"}

player2 = {display_name =>“darren collison”,“position”=>“PG”}

Would it be something like

它会是什么样的

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?

有没有更好的方法来实现这一目标?

Thanks!

1 个解决方案

#1


7  

Given your input:

鉴于您的意见:

input =  [
  { "last_name"=>"Gay", ... }, 
  { "last_name"=>"Collison", ...}
]

If all of those keys (last_name, first_name, display_name) are present in the Player model, you can just:

如果所有这些键(last_name,first_name,display_name)都存在于Player模型中,您可以:

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:

由于create将使用要分配的属性的哈希值。但是,更好的是,你甚至不需要迭代:

Player.create(input)

ActiveRecord will go through them all if you give it an array of hashes.

如果你给它一个哈希数组,ActiveRecord将全部通过它们。

#1


7  

Given your input:

鉴于您的意见:

input =  [
  { "last_name"=>"Gay", ... }, 
  { "last_name"=>"Collison", ...}
]

If all of those keys (last_name, first_name, display_name) are present in the Player model, you can just:

如果所有这些键(last_name,first_name,display_name)都存在于Player模型中,您可以:

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:

由于create将使用要分配的属性的哈希值。但是,更好的是,你甚至不需要迭代:

Player.create(input)

ActiveRecord will go through them all if you give it an array of hashes.

如果你给它一个哈希数组,ActiveRecord将全部通过它们。