Writing an age checker program, am adding code to check for input error.
I'm having a problem understanding what the issue is with a section of code, ruby returns a (NoMethodError) for .to_i methods passed into some string objects.
The full code is as follows;
def calculate_difference(year,month,day)
years = Time.new.year - year
months = Time.new.month - month
days = Time.new.day - day
if months == 0
if days < 0
age = years - 1
elsif days >= 0
age = years
end
elsif months > 0
age = years
else
age = years - 1
end
end
puts "What year were you born in?"
year = gets.chomp
while year.to_i < 1900 or year.to_i > Time.new.year - 5
puts "Please enter a year between 1900 and 5 years ago"
year = gets.chomp
end
puts "And the month?"
month = gets.chomp
while month.to_i > 12 or month.to_i <= 0
puts "MONTH please, numbers from 1 to 12..."
month = gets.chomp
end
puts "And the day number?"
day = gets.chomp
#The offending block of code:
if month.to_i = 1 or month.to_i = 3 or month.to_i = 5 or month.to_i = 7 or month.to_i = 8 or month.to_i = 10 or month.to_i = 12
while day.to_i > 31 or day.to_i <= 0
puts "Your month of birth has 31 days, please select a date within the correct range"
day = gets.chomp
end
end
if month.to_i = 2
while day.to_i > 28 or day.to_i < 0
puts "Incorrect day selected for February"
day = gets.chomp
end
end
stringdate = year+month+day
stringdate = stringdate.gsub(" ","")
while stringdate.length != 8
puts "in number format please: yyyy/mm/dd"
puts "What year were you born in?"
year = gets.chomp
puts "And the month?"
month = gets.chomp
puts = "And the day number?"
day = gets.chomp
end
year = year.to_i
month = month.to_i
day = day.to_i
puts "Congratulations, you are #{calculate_difference(year,month,day)} years old."
I'm not sure why it is throwing back an error, as I'm sure strings integers respond to the .to_i method.