iterate through array of hashes in ruby -
iterate through array of hashes in ruby -
so if have array of hashes 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 iterate through array iterate through each hash have this:
player1 = {display_name=>"rudy gay", "position"=>"sf"}
player2 = {display_name=>"darren collison", "position"=>"pg"}
would
input.each |x| player.create(name: x['display_name'], position: x['position'] end
(assuming have player model)
is there improve way accomplish this?
thanks!
given input:
input = [ { "last_name"=>"gay", ... }, { "last_name"=>"collison", ...} ]
if of keys (last_name, first_name, display_name) nowadays in player
model, can just:
input.each |x| player.create(x) end
since create
take hash of attributes assign. but, better, don't need iterate:
player.create(input)
activerecord go through them if give array of hashes.
ruby-on-rails ruby arrays hash
Comments
Post a Comment