main
1require 'spec_helper'
2require 'csv'
3require 'ostruct'
4#In weather.dat you’ll find daily weather data for Morristown, NJ for June 2002.
5#Download this text file, then write a program to output the day number (column one)
6#with the smallest temperature spread (the maximum temperature is the second column, the minimum the third column).
7
8class Tuple
9 include Comparable
10 attr_reader :key, :value
11
12 def initialize(key:, max:, min:)
13 @key = key
14 @value = (max - min).abs
15 end
16
17 def <=>(other)
18 value <=> other.value
19 end
20end
21
22class Team
23 def self.map_from(row)
24 return nil if row[1].nil?
25 Tuple.new(key: row[1], max: row[6].to_i, min: row[8].to_i)
26 end
27end
28
29class Day
30 def self.map_from(row)
31 Tuple.new(key: row[0], max: row[1].to_f, min: row[2].to_f)
32 end
33end
34
35class Spread
36 include Enumerable
37
38 def initialize(filename, mapper)
39 @file_path = File.join(File.dirname(__FILE__), "../fixtures", filename)
40 @mapper = mapper
41 end
42
43 def each
44 open_file do |file|
45 file.each_line.with_index do |line, index|
46 next if index == 0
47 next if line.chomp.empty?
48 row = mapper.map_from(line.split)
49 next if row.nil?
50 yield row
51 end
52 end
53 end
54
55 private
56
57 def open_file
58 file = File.new(file_path)
59 yield file
60 ensure
61 file.close
62 end
63
64 attr_reader :file_path, :mapper
65end
66
67describe "weather.dat" do
68 subject { Spread.new('weather.dat', Day) }
69
70 it 'returns the day with the smallest temperature spread' do
71 expect(subject.min.key).to eql('14')
72 end
73end
74
75# Part Two: Soccer League Table
76# The file football.dat contains the results from the English Premier League for 2001/2.
77# The columns labeled ‘F’ and ‘A’ contain the total number of goals scored for and against each team in that season (so Arsenal scored 79 goals against opponents, and had 36 goals scored against them). Write a program to print the name of the team with the smallest difference in ‘for’ and ‘against’ goals.
78#
79describe "football.dat" do
80 subject { Spread.new('football.dat', Team) }
81
82 it 'returns the day with the smallest temperature spread' do
83 expect(subject.min.key).to eql('Aston_Villa')
84 end
85end