0

I have the following code that returns the # of days in any given month, which works fine unless someone types in something that isn't a date, or they format the date wrong. To remedy this I want to send out an error message for an invalid input, but I don't know how. So how do I create an error message for this small app?

   #type in the month and year you want like so ---> "Feb 2034"

require 'date'

input = gets.chomp

inputArray = input.split(" ").to_a

textMonth = inputArray[0]
textYear = inputArray[1]

startOfMonth = Date.strptime(input, "%b %Y")
nextMonth = startOfMonth.next_month
endOfMonth = nextMonth - 1
daysInMonth = (endOfMonth - startOfMonth + 1).to_i

puts "#{textMonth} of year #{textYear} has #{daysInMonth} days!"
Ryan
  • 151
  • 11
  • 1
    A better thing to do Ryan will be to create an exception. Just extend StandardError, create your own error class and then raise an exception with a detail message. – theterminalguy May 16 '18 at 17:29
  • I'm a total noob, could you type out a code example? – Ryan May 16 '18 at 20:24

3 Answers3

1

Probably the best way to do this is putting your input in a while loop, prompting for a new answer every time the input isn't what you expected it to be.

To check the input you should use a Regexp. Here's an explanation how to write a regexp to match a date.

Viktor
  • 2,623
  • 3
  • 19
  • 28
  • So how would I add the code in this comment, to my code above in my post ---> def valid_date( str, format="%m/%d/%Y" ) Date.strptime(str,format) rescue false end – Ryan May 16 '18 at 22:55
1

For Creating a Custom Error refer below code: Here I create and raise InvalidDateError for the wrong date input.

   #type in the month and year you want like so ---> "Feb 2034"
class InvalidDateError < StandardError
end

require 'date'
require 'pry-byebug'
input = gets.chomp

inputArray = input.split(" ").to_a

textMonth = inputArray[0] 
textYear = inputArray[1]
begin
    startOfMonth = Date.strptime(input, "%b %Y")
    nextMonth = startOfMonth.next_month
    endOfMonth = nextMonth - 1
    daysInMonth = (endOfMonth - startOfMonth + 1).to_i
    puts "#{textMonth} of year #{textYear} has #{daysInMonth} days!"
rescue StandardError=> e
    raise InvalidDateError.new("Invalid Date : #{input}")
end

If you don't want to raise an error and only want to show error message then replace raise InvalidDateError.new("Invalid Date : #{input}") with puts "Invalid Date : #{input}"

rahul mishra
  • 1,390
  • 9
  • 16
1

As suggested by Viktor, and stolen :) from crantok

require 'date'
date_valid = false

while !date_valid
  puts 'Insert date as yyyy-mm-dd:'
  input_date = gets.chomp

  begin
    parsed_date = Date.parse(input_date)
    date_valid = true
  rescue ArgumentError
    puts 'format error'
  end
end

month = parsed_date.month
year = parsed_date.year
days_in_month = Date.new(year, month, -1).day
puts "In #{year} month #{month} has #{days_in_month} days"
iGian
  • 11,023
  • 3
  • 21
  • 36