简体   繁体   中英

How do I add values from two different arrays of hashes together?

I have two arrays of hashes. The keys for the hashes are different:

player_scores1 = [{:first_name=>"Bruce", :score => 43, :time => 50},
                  {:first_name=>"Clark", :score => 45, :minutes => 20}]

player_scores2 = [{:last_name=>"Wayne", :points => 13, :time => 40},
                  {:last_name=>"Kent", :points => 3, :minutes => 20}]

I'd like to create a new array of hashes which adds up :score and :points together and assign it to a key called :score. I'd also like to combine the :first_name and :last_name and assign it to a key called :full_name. I want to discard any other keys.

This would result in this array:

all_players = [{:full_name => "Bruce Wayne", :score => 56}, 
               {:full_name => "Clark Kent", :score => 48}]

Is there an elegant way to do this?

Something like this:

player_scores1.zip(player_scores2).map { |a,b|
    {
        :full_name => a[:first_name]+' '+b[:last_name],
        :score => a[:score]+b[:points]
    }
}

The code you're looking for is:

final = []
player_scores1.each_index do |index|
  entry_1 = player_scores1.values(index)
  entry_2 = player_scores2.values(index)[:first_name]
  score = entry_1[:score] + entry_2[:points]
  final << {:full_name => "#{entry_1[:first_name]} #{entry_2[:last_name]}", :score => score }
end

Any suggestions on tightening this up would be much appreciated!

This works. I don't if that's elegant enough though.

player_scores1 = [{:first_name=>"Bruce", :score => 43, :time => 50},
                  {:first_name=>"Clark", :score => 45, :minutes => 20}]

player_scores2 = [{:last_name=>"Wayne", :points => 13, :time => 40},
                  {:last_name=>"Kent", :points => 3, :minutes => 20}]

p (0...[player_scores1.length, player_scores2.length].min).map {|i| {
    :full_name => player_scores1[i][:first_name] + " " + player_scores2[i][:last_name], 
    :score => player_scores1[i][:score] + player_scores2[i][:points]
}}

This example on Codepad .

This uses zip with a block to loop over the hashes, joining the names and summarizing:

all_players = []
player_scores1.zip(player_scores2) { |a, b| 
  all_players << { 
    :full_name => a[:first_name] + ' ' + b[:last_name],
    :score     => a[:score] + b[:points]
  } 
}
all_players # => [{:full_name=>"Bruce Wayne", :score=>56}, {:full_name=>"Clark Kent", :score=>48}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM