在一般情況下,你應該嘗試將數據inout邏輯與數據驗證和後續處理分開。這樣,你的方法只關心一件事情,這使得它們更容易推理,從而更加強大。
在這裏,我們介紹一個valid_date_string?
方法,該方法檢查傳遞的input
對象是否是有效的日期字符串。
require 'date'
def valid_date_string?(input)
# First, we check that the given input is of the expected type.
# We do this here explicitly since we are validating a String. Most
# of the time, you would rely on duck typing instead.
return false unless input.is_a?(String)
# Then, we ensure roughly valid syntax (i.e. it looks like a date)
return false unless input =~ /\A\d+-\d+-\d+\z/
# Then, we "parse" it and split it into an array of year, month, day...
parts = input.split('-').map(&:to_i)
# ...and validate that this represents a valid date
Date.valid_date?(*parts)
end
在這個解決方案,我十分小心不要依賴例外程序流,因爲這通常是在,因爲它會導致未被發現的錯誤和有表現不佳皺起了眉頭。
然後,我們可以使用一些輸入迴路這種方法要求用戶輸入一些值
def get_valid_date
loop do
input = gets.chomp
return input if valid_date_string?(input)
# Here, the user entered an invalid date. We can now do our
# error handling and try again.
puts "Invalid date given. Please try again..."
end
end
my_valid_date_string = get_valid_date
TY爲輸入,它的大加讚賞 –