How to check if a string is a year
With a bit of feat / regex magic, something like the following will allow you to check not only if a string is numeric (first criteria for a valid year), but also if it falls within a specific range of years:
def is_valid_year?(date_str, start=1900, end=2099)
date_str.grep(/^(\d)+$/) {|date_str| (start..end).include?(date_str.to_i) }.first
end
The above function will return nil
for any string with non-numeric characters, false
for those that are numeric but outside the provided range, and true
for valid strings, the year.
source to share
Seems like a more direct question: how do you validate that the user is entering a string that matches the number between 1582 and 2500 (say). You can do it like this:
date_string.scan(/\D/).empty? and (1582..2500).include?(date_string.to_i)
so you can choose which is a reasonable year too, for example 800 is really a valid answer in your application? or 3000?
source to share
Date.parse(string_of_date).gregorian?
Also, check out the documentation for the Date class .
source to share
Wanting to parse an integer from a string is a fairly common question in Ruby. Probably because there is no perfect approach. Maybe he deserves his tag!
Check if string is a quoted integer using Ruby?
How do I get the second integer in a Ruby string with the to_i parameter?
Extracting and multiple integers from user input string in Ruby?
How can I convert an integer input string to an integer in Ruby?
source to share