Skip to content

Instantly share code, notes, and snippets.

@wmwong
Created September 24, 2013 02:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save wmwong/6679717 to your computer and use it in GitHub Desktop.
module DataMunger
# This method uses the given regex to parse the data in the given filename
# to determine the minimum spread.
# The first match of the regex is the data to return.
# The second and third match is used to find the spread.
def min_spread(filename, regex)
result = nil
min_spread = nil
# Go through each line and parse the data.
File.open(filename, "r").each_line do |line|
matches = line.match(regex)
# If there is data, check the spread.
# Update the min_spread if this spread is less then the previously found
# spread.
if matches
spread = (matches[2].to_i - matches[3].to_i).abs
if min_spread.nil? || spread < min_spread
result = matches[1]
min_spread = spread
end
end
end
result
end
end
include DataMunger
puts min_spread("weather.dat", /^\s+(\d+)\s+(\d+)\s+(\d+)/)
puts min_spread("football.dat", /[^a-z_]+([a-z_]+).+\s+(\d+)\s+-\s+(\d+)/i)
team = nil
min_spread = nil
# Create a regex for grabbing the data from the line.
regex = /[^a-z_]+([a-z_]+).+\s+(\d+)\s+-\s+(\d+)/i
# Go through each line and parse the data.
File.open("football.dat", "r").each_line do |line|
matches = line.match(regex)
# If there is data, check the spread.
# Update the min_spread if this spread is less then the previously found
# spread.
if matches
spread = (matches[2].to_i - matches[3].to_i).abs
if min_spread.nil? || spread < min_spread
team = matches[1]
min_spread = spread
end
end
end
puts team
day = nil
min_spread = nil
# Create a regex for grabbing the data from the line.
regex = /^\s+(\d+)\s+(\d+)\s+(\d+)/
# Go through each line and parse the data.
File.open("weather.dat", "r").each_line do |line|
matches = line.match(regex)
# If there is data, check the spread.
# Update the min_spread if this spread is less then the previously found
# spread.
if matches
spread = matches[2].to_i - matches[3].to_i
if min_spread.nil? || spread < min_spread
day = matches[1].to_i
min_spread = spread
end
end
end
puts day
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment