public
Created

kata 4: data munging (part 3)

  • Download Gist
kata4_3.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
class TabFile < File
def initialize(file, regexp)
super(file, "r")
@regexp = regexp
end
 
def tab_data
data = Array.new
self.each { |line|
line_match = @regexp.match(line)
if !line_match.nil? then
data << line_match.captures.collect { |v| v.match(/^\d+$/)? v.to_i : v }
end
}
return data
end
end
 
puts TabFile.new("weather.dat", /^\s+([0-9]+)\s+([0-9]+)[*]?\s+([0-9]+)[*]?/).tab_data.min {|a,b| a[1]-a[2] <=> b[1]-b[2] }[0]
 
puts TabFile.new("football.dat", /^\s+[0-9]+[.]\s([a-zA-Z_]+)\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s+-\s+([0-9]+)/).tab_data.min { |a,b| (a[1]-a[2]).abs <=> (b[1]-b[2]).abs }[0]

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.