Ruby: How to check if the string is correct?

I am pulling the data from the feed for which I have no control, and I need to check if the line I am giving is the real time.

In most cases, I correctly send something like โ€œ2:35โ€ or โ€œ15:41โ€, but in other cases it looks like โ€œAMโ€ or โ€œPMโ€ (and without digits) ... so I ultimately just need to ignore them.

So how can I check if the data is valid time?

+6
string ruby ruby-on-rails time
source share
2 answers

You can use Time.parse () and check for an ArgumentError exception for invalid times.

An added benefit is that you also have time in an easy-to-use format, if valid!

+8
source share

You didnโ€™t specify exactly what you think is a valid time (for example, whether to take extra seconds), so here you can assume:

data =~ /^([01]?[0-9]|2[0-3])\:[0-5][0-9]$/ 
+7
source share

All Articles