iterate through array of hashes in ruby

后端 未结 1 1908
误落风尘
误落风尘 2021-01-18 16:53

so if I have an array of hashes like so: (ruby beginner)

input =  [

{\"last_name\"=>\"Gay\", \"first_name\"=>\"Rudy\", \"display_name\"=>\"Rudy Gay         


        
相关标签:
1条回答
  • 2021-01-18 17:15

    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:

    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 will go through them all if you give it an array of hashes.

    0 讨论(0)
提交回复
热议问题