Forum: Ruby on Rails How to check an input String is a number or not in ruby?

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Joshua A. (Guest)
on 2006-05-22 08:03
How to check an input String is a number or not in ruby?
Thanks in advance,
Bill W. (Guest)
on 2006-05-22 08:53
(Received via mailing list)
Hi Joshua,

joshua asem wrote:

> How to check an input String is a number or not in ruby?

First, I'm going to assume you're asking about how to do that in a Rails
as opposed to straight Ruby.  If you're looking for Ruby language
support, a
better place to ask your question would be

You didn't say whether you want / need to check it on the client- or on

If server-side works for you, and it's definitely the easiest, check the
documentation on validates_numericality_of at
You'd use that validation in your model.

If client-side, you'll probably want to use pattern matching in a
Javascript.  What pattern you'd validate against would depend on the
you're expecting / allowing.  The documentation at
should help you understand how to include the JS in your Rails app.

Joshua A. (Guest)
on 2006-05-22 09:16
  Thanks for your suggestion,
  But the exact thing i want is to validate using ruby script not the
javascript and also not the validates_numericality_of. As I was coding
differently little bit to support legacy database and without using the
model directly. The results get returned from the stored procs in the
hash form.
  So i just wanted to do it generally using ruby script.
  If you have the idea in ruby script , exactly the piece of code for
validating number like isNumber(). Please reply with small piece of code
if you don;t mind

Thanks in advance.
Tarmo =?ISO-8859-1?Q?T=E4nav?= (Guest)
on 2006-05-23 08:17
(Received via mailing list)
On E, 2006-05-22 at 07:16 +0200, joshua asem wrote:
> if you don;t mind
> Thanks in advance.
> joshua...

You can use Integer(string_containing_number) which raises an
exception if the string can not be converted to a number.

Or you could use a regular expression to check that the string
only contains a number:

if string_containing_number =~ /^\d+$/
  # is numeric, safe to use string_containing_number.to_s
  #  (which would return 0 in case of failure to convert)
  # not numeric

Tarmo Tänav <removed_email_address@domain.invalid>
This topic is locked and can not be replied to.