循环直到用户以正确的格式输入他的生日

时间:2015-10-05 10:14:30

标签: ruby

我[sic]用户要遵守格式(dd.mm.yyyy)。我想重复询问用户他的生日,直到他以正确的格式进入他的生日。在用户以正确的格式输入生日之前,我将如何提出用户输入循环的问题?我可以为用户输入设置哪些条件?

这是我写的小程序。

puts "What is your birthday? (dd.mm.yyyy)"
user_input = gets.chomp

user_array = user_input.split(".")
uyyyy = user_array[2]
umm = user_array[1]
udd = user_array[0]

y = Time.now.year
m = Time.now.month
d = Time.now.day

require 'Date'
a = Date.new(y.to_i, m.to_i, d.to_i) - Date.new(uyyyy.to_i, umm.to_i, udd.to_i,)
sec = (a * 24 * 60 * 60).to_i

if a < 0
  puts "You are born in the future!"
  puts "You will be born in #{a} days"
else
  puts "Your year is #{uyyyy}! Your month is #{umm}! Your day is #{udd}!"
  puts "Todays year is #{y}! Todays month is #{m}! Todays day is #{d}!"
  puts "You are #{a.to_int/365} years, #{m} month and #{d} days old"    
  puts "You are #{sec} seconds old!"
end

2 个答案:

答案 0 :(得分:0)

while true
  puts "What is your birthday? (dd.mm.yyyy)"
  user_input = gets.chomp
  break if user_input =~ /\A\d{2}\.\d{2}\.\d{4}\z/
end
udd, umm, uyyyy = user_input.split(".")

答案 1 :(得分:0)

你在这里:

h1 {
    page-break-before: always;
}