-
-
Save jli-hashrocket/7554184 to your computer and use it in GitHub Desktop.
| require 'pry' | |
| games = [ | |
| { | |
| home_team: "Patriots", | |
| away_team: "Broncos", | |
| home_score: 7, | |
| away_score: 3 | |
| }, | |
| { | |
| home_team: "Broncos", | |
| away_team: "Colts", | |
| home_score: 3, | |
| away_score: 0 | |
| }, | |
| { | |
| home_team: "Patriots", | |
| away_team: "Colts", | |
| home_score: 11, | |
| away_score: 7 | |
| }, | |
| { | |
| home_team: "Steelers", | |
| away_team: "Patriots", | |
| home_score: 7, | |
| away_score: 21 | |
| } | |
| ] | |
| scores = {"Patriots" => [0,0], | |
| "Broncos" => [0,0], | |
| "Colts" => [0,0], | |
| "Steelers" => [0,0]} | |
| games.each do |game| | |
| if game[:home_score] > game[:away_score] | |
| scores[game[:home_team]][0] += 1 | |
| scores[game[:away_team]][1] += 1 | |
| else | |
| scores[game[:away_team]][0] += 1 | |
| scores[game[:home_team]][1] += 1 | |
| end | |
| end | |
| scores = scores.sort_by{|key, val| -val[0]} | |
| scores.each do |key, val| | |
| puts "#{key} #{val[0]} wins, #{val[1]} losses" | |
| end |
Some duplication could then be removed by created a variable to hold the value of a default_score:
default_score = { wins: 0, losses: 0 }
scores = {
"Patriots" => default_score.clone,
"Broncos" => default_score.clone,
"Colts" => default_score.clone,
"Steelers" => default_score.clone
}We need to call the clone method on our default_score hash so that they aren't all pointing to the same Hash object. If we didn't call clone on the default_score Hash, we would be change the scores for every team any time that we updated any team.
For example:
scores = {
"Patriots" => default_score,
"Broncos" => default_score,
"Colts" => default_score,
"Steelers" => default_score
}
scores["Patriots"] #=> { wins: 0, losses: 0 }
scores["Broncos"] #=> { wins: 0, losses: 0 }
scores["Patriots"][:wins] += 1
scores["Patriots"] #=> { wins: 1, losses: 0 }
scores["Broncos"] #=> { wins: 1, losses: 0 }You can read more about mutable and immutable objects at http://rubylearning.com/satishtalim/mutable_and_immutable_objects.html
Spending a little extra time to think of descriptive variable names can sometimes dramatically improve the readability of your code.
For example, if we change the variables key and val here
scores = scores.sort_by { |team, record| -record[:wins] }
scores.each do |team, record|
puts "#{team} #{record[:wins]} wins, #{record[:losses]} losses"
endIf we're just looking at those pieces of code, we don't need to leave this spot to try and figure out what key and val are going to represent.
I would probably use a hash to store this data so that I could label the
wins and the losses.
The app would now look like this: