ruby on rails - Create a hash containing arrays -


i trying create hash called winners.

i have model called arcade each has games associated it. trying create hash of winners matched each prize.

arcade.rb is:

def prizes_by winner   winners = {}   self.games.each |g|    high_score = g.high_score    if high_score      winners[high_score.user] ||= []      winners[high_score.user] << g    end   end end  

when hash doesn't contain key each high_score.user.

i expect hash looks like:

winners{    user1 => [game1, game2, game3...]    user2 => [game 4]    user3 => [game10, game11]    ... } 

how this? using each_with_object:

def prizes_by winner   games.each_with_object({}) |game, hash|     if high_score = game.high_score       (hash[high_score.user] ||= []).push(game)     end   end end 

i haven't tested this.


Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -