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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
7a5f8cc44b8b6da7a415a2c5bcdc14be?d=identicon&s=25 Joshua Asem (joshua-asem)
on 2006-05-22 06:03
How to check an input String is a number or not in ruby?
Thanks in advance,
Joshua
2b891e820c238ded365d035771603f21?d=identicon&s=25 Bill Walton (Guest)
on 2006-05-22 06: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
app
as opposed to straight Ruby.  If you're looking for Ruby language
support, a
better place to ask your question would be
http://groups.google.com/group/comp.lang.ruby

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

If server-side works for you, and it's definitely the easiest, check the
documentation on validates_numericality_of at
http://api.rubyonrails.org/.
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
format
you're expecting / allowing.  The documentation at
http://api.rubyonrails.com/classes/ActionView/Help...
should help you understand how to include the JS in your Rails app.

hth,
Bill
7a5f8cc44b8b6da7a415a2c5bcdc14be?d=identicon&s=25 Joshua Asem (joshua-asem)
on 2006-05-22 07:16
Hi,
  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.
joshua...
0f630dfa170eb15cb9bd041783b6551f?d=identicon&s=25 Tarmo =?ISO-8859-1?Q?T=E4nav?= (Guest)
on 2006-05-23 06: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)
else
  # not numeric
end


--
Tarmo Tänav <tarmo@itech.ee>
This topic is locked and can not be replied to.