"Gay", "first_name"=>"...">

Iterate through a hash array in ruby

so if I have an array of hashes, for example: (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} ] 

like iterating through an array, as well as iterating over each hash to have something like this:

player1 = {display_name => "rudy gay", "position" => "SF"}

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

Will it be something like

 input.each do |x| Player.create(name: x['display_name'], position: x['position'] end 

(if I have a player model)

Is there a better way to achieve this?

Thanks!

+5
source share
1 answer

Given your input:

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

If all these keys (last_name, first_name, display_name) are present in the Player model, you can simply:

 input.each do |x| Player.create(x) end 

Since create will accept an attribute hash for the assignment. But, even better, you don’t even need to repeat:

 Player.create(input) 

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

+7
source

Source: https://habr.com/ru/post/1206128/


All Articles