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


#1

How to check an input String is a number or not in ruby?
Thanks in advance,
Joshua


#2

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/Helpers/JavaScriptHelper.html
should help you understand how to include the JS in your Rails app.

hth,
Bill


#3

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…


#4

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 removed_email_address@domain.invalid