K4Weather Solution
From DojoWiki
The final solution is directly below, which was refactored from this solution
class Weather
def getMinTempDiff(filename)
minTempDifference = maxvalue
File.open(filename).each { |line|
maxValue = getByIndex(line, 1)
minValue = getByIndex(line, 2)
if (maxValue == nil || minValue == nil)
next
end
difference = (maxValue - minValue)
if (difference < minTempDifference)
minTempDifference = difference
end
}
return minTempDifference
end
def getByIndex( line, index )
str = line.split(' ')[index]
if (str != nil && str.index("*") != nil)
str = str.slice(0, str.index("*"))
end
if (str != nil)
begin
value = Float(str)
rescue
value = nil
end
end
value
end
def maxvalue
return 99999
end
end
require 'test/unit'
require 'weather.rb'
class TestWeather < Test::Unit::TestCase
def test_output
weather = Weather.new
s=2
assert_equal(2, weather.getValue('K4Weather.txt'))
end
end
[edit]
Original Solution
class Weather
def getValue(filename)
tempValue = nil
File.open(filename).each { |line|
maxStr = line.split(' ')[1]
minStr = line.split(' ')[2]
if (maxStr != nil && maxStr.index("*") != nil)
maxStr = maxStr.slice(0, maxStr.index("*"))
end
if (minStr != nil && minStr.index("*") != nil)
minStr = minStr.slice(0, minStr.index("*"))
end
if (minStr != nil && maxStr != nil)
begin
minValue = Float(minStr)
rescue
puts "Failed " + $!
end
begin
maxValue = Float(maxStr)
rescue
puts "Failed " + $!
end
if (maxValue != nil && minValue != nil)
value = (maxValue - minValue)
if (tempValue == nil)
tempValue = minValue
end
if (value < tempValue)
tempValue = value
end
end
end
puts tempValue.to_s
return 2
}
end
end
