Created
November 20, 2013 16:29
-
-
Save hchood/7566207 to your computer and use it in GitHub Desktop.
Ruby Fundamentals - Non-core challenge (leaderboard from game data)
This file contains 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
# Ruby Fundamentals III - Non-core challenge | |
# Calculate the leaderboard in the following format (data is exaggerated, but the Patriots are on top!) | |
# The list should be sorted by number of wins. | |
# 1. Patriots 16 wins, 0 losses | |
# 2. Colts, 8 wins, 8 losses | |
# 3. Broncos, 4 wins, 12 losses | |
# 4. Steelers, 2 wins, 14 losses | |
require 'pry' | |
require 'awesome_print' | |
# GAME DATA | |
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 | |
} | |
] | |
# TEAM CLASS & METHODS | |
class Team | |
attr_reader :name, :wins, :losses | |
def initialize(name) | |
@name = name | |
@wins = 0 | |
@losses = 0 | |
end | |
def win | |
@wins += 1 | |
end | |
def lose | |
@losses += 1 | |
end | |
end | |
def update_team_results(winner, loser, teams, game) | |
# Question: why do I need to pass in teams & game to this method? This is a lot of parameters. | |
# Any way to scope variables differently so I only have to pass in winner & loser? | |
teams.each do |team| | |
team.win if game[winner] == team.name | |
team.lose if game[loser] == team.name | |
end | |
end | |
# INITIALIZE TEAM OBJECTS, CREATE TEAMS ARRAY | |
patriots = Team.new("Patriots") | |
broncos = Team.new("Broncos") | |
colts = Team.new("Colts") | |
steelers = Team.new("Steelers") | |
teams = [patriots, broncos, colts, steelers] | |
# UPDATE TEAMS' WINS AND LOSSES BASED ON GAME DATA IN GAME ARRAYS | |
games.each do |game| | |
if game[:home_score] > game[:away_score] | |
update_team_results(:home_team, :away_team, teams, game) | |
else | |
update_team_results(:away_team, :home_team, teams, game) | |
end | |
end | |
# OUTPUT LEADERBOARD | |
teams.sort_by!{|team| [-team.wins, team.losses]} | |
teams.each do |team| | |
puts "#{teams.index(team)+1}. #{team.name} - #{team.wins} wins, #{team.losses} losses" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment