Actually, even better try running this version of my program and your see that inputs of 1 1/2 and "1 1/2" both work and both give the same answer.
Code:
class FractionTest
NUMBER_AND_FRACTION = /(\d+)\s+(\d+\/\d+)/
FRACTION_ONLY = /(\d+)\/(\d+)/
NUMBER_ONLY = /(\d+\.*\d*)/
def test(number)
case number
when NUMBER_AND_FRACTION
number_and_fraction(number)
when FRACTION_ONLY
fraction_only(number)
when NUMBER_ONLY
number_only(number)
else
puts "no match"
end
puts "--------------"
end
private
def number_and_fraction(number)
parts = number.match(NUMBER_AND_FRACTION)
result = parts[1].to_f + process_fraction(parts[2])
puts "#{number} contains the number #{parts[1]} "
puts "and the fraction #{parts[2]} "
puts "and is equal to #{result}."
end
def fraction_only(number)
result = process_fraction(number)
puts "#{number} contains the fraction #{number} "
puts "and is equal to #{result}."
end
def number_only(number)
result = number.match(NUMBER_ONLY)[0].to_f
puts "#{number} contains the number #{number}"
puts "and is equal to #{result}."
end
def process_fraction(fraction)
parts = fraction.match(FRACTION_ONLY)
numerator = parts[1].to_f
denominator = parts[2].to_f
return numerator / denominator
end
end
ft = FractionTest.new
puts "Enter a number"
number_to_test = gets
ft.test(number_to_test)
Actually, playing with that I notice that there is a formatting issue as the gets is recovering the end of line character and that is causing my output to step down a line at this point:
Code:
puts "#{number} contains the number #{parts[1]} "
So 1 1/2 is generating:
1 1/2
contains the number 1
Instead of the intended
1 1/2 contains the number 1
And indeed a chomp fixes that for example by altering the last line to:
Code:
ft.test(number_to_test.chomp)
Bookmarks