编写年龄检查程序,添加代码以检查输入错误。
我在解决问题的一部分代码时遇到问题,ruby为传递给某些字符串对象的.to_i方法返回一个(NoMethodError)。
完整代码如下;
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
#违规代码块:
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."
我不确定为什么会抛出错误,因为我确定字符串整数会响应.to_i方法。
答案 0 :(得分:2)
错误消息显示&#34;未定义的方法&#39; myBook.number() = 5
myChapter.number() = 2
myPage.number() = 8
&#39;&#34;而不是to_i=
&#39;
这是因为Ruby解释了单个&#34; =&#34;好像你想在假设的字段to_i
上调用setter方法:
to_i
答案 1 :(得分:0)
&#34; =
&#34;是作业。
&#34; ==
&#34;检查它们是否相等并返回true或false。
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
或更具可读性:
if [1, 3, 5, 7, 8, 10, 12].include? month.to_i
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 2 == month.to_i
while day.to_i > 28 or day.to_i < 0
puts "Incorrect day selected for February"
day = gets.chomp
end
end