From: sto.mar@... Date: 2012-08-04T22:41:30+09:00 Subject: Re: OptionParser error handling (InvalidArgument) Am 04.08.2012 01:31, schrieb Panagiotis Atmatzidis: > A bit off-topic now. In your next email you told me that you dislike > raising an exception in order to identify an integer. A second > approach I found online was using regexp. That's what I did in my version, too. > However this was the answer I got from a user at 'stackoverflow' > which convinced that this is the right way to go in ruby: > > "Sarah: you can use a Regex but in order to handle all the cases that > Ruby does when parsing integers (negative numbers, hex, octal, > underscores e.g. 1_000_000) it would be a very big Regex and easy to > get wrong. Integer() is canonical because with Integer ()you know > for sure that anything that Ruby considers an integer literal will be > accepted, and everything else will be rejected. Duplicating what the > language already gives you is arguably a worse code smell than using > exceptions for control. – Avdi " from > http://stackoverflow.com/questions/1235863/test-if-a-string-is-basically-an-integer-in-quotes-using-ruby Imo there is no "canonical" way that fits all use cases. Here, in connection with command line arguments, I prefer using a regexp (probably as a second choice after using the Integer cast from optparse): I do not expect an octal integer as user input, the regexp is rather simple, and the approach is flexible. I can for example test for integers or for nonnegative integers, with /\A[+-]?\d+\Z/ === str or /\A[+]?\d+\Z/ === str Partly a matter of taste. --