Menu
Coddy logo textTech

Recap - Sports League

Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 31 of 57.

challenge icon

Challenge

Hard

Build a small league table. Team includes Comparable: a team is greater when it has more points (3 for a win, 1 for a draw), then a better goal difference, then an earlier name alphabetically. record(scored, conceded) updates the team, and to_s returns Reds 7 pts, +3. League includes Enumerable: each yields the teams, play(line) records a result such as Reds 2-1 Blues for both teams (creating a team the first time its name appears), and table returns the teams from best to worst using sort. The module Rankable with leader (the best team, from max) is included in League.

The supplied code passes every input line to play, then prints the table with positions (1. Reds 7 pts, +3), the leader, and the teams without a win in any game, found with select.

Your code goes in rankable.rb, team.rb and league.rb. main.rb holds the supplied input/output code and cannot be edited.

Try it yourself

require_relative 'rankable'
require_relative 'team'
require_relative 'league'

# Supplied input/output code: keep it as it is
input = []
while (line = gets)
  input << line.chomp
end
league = League.new
input.each { |line| league.play(line) }
league.table.each_with_index { |t, i| puts "#{i + 1}. #{t}" }
puts "leader: #{league.leader&.name}"
winless = league.select { |t| t.wins.zero? }.map(&:name).sort
puts "no wins: #{winless.empty? ? "none" : winless.join(", ")}"

All lessons in Object Oriented Programming

Practice on your own: Online Ruby compiler