How do I add values from two different arrays of h

2019-05-14 11:01发布

问题:

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?

回答1:

Something like this:

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


回答2:

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!



回答3:

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.



回答4:

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}]


标签: ruby arrays hash