Last active
December 28, 2015 19:59
-
-
Save jli-hashrocket/7554184 to your computer and use it in GitHub Desktop.
game data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
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.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some duplication could then be removed by created a variable to hold the value of a
default_score:We need to call the
clonemethod on ourdefault_scorehash so that they aren't all pointing to the same Hash object. If we didn't callcloneon thedefault_scoreHash, we would be change the scores for every team any time that we updated any team.For example:
You can read more about mutable and immutable objects at http://rubylearning.com/satishtalim/mutable_and_immutable_objects.html