Manan Shah
Manan Shah

Reputation: 1098

Check string is a valid number or not in ruby

I want to check weather variable contains a valid number or not.

I can validate correctly for null and blank but can not validate text as a "Integer"...

I tried:

if(params[:paramA].blank? || (params[:paramA].is_a?(Integer)) )

I have also tried is_numeric, is_numeric(string), is_number? and other ways... but did not get success...

Upvotes: 0

Views: 1523

Answers (4)

xlembouras
xlembouras

Reputation: 8295

In rails you can use the numeric? method on a String or Integer or Float which does exactly what you need.

123.numeric?
# => true
123.45.numeric?
# => true
"123".numeric?
# => true
"123.45".numeric?
# => true
"a1213".numeric?
# => false

UPDATE

My bad, I had a dirty environment, the above works if mongoid version 3 and above is loaded.

Upvotes: 1

scaryguy
scaryguy

Reputation: 7960

If the thing you want to do is this:

I want to check weather variable contains a valid number or not.

You can get it with regex. See it here

s = 'abc123'

if s =~ /[-.0-9]+/         # Calling String's =~ method.
  puts "The String #{s} has a number in it."
else
  puts "The String #{s} does not have a number in it."
end

Upvotes: 1

Danil Speransky
Danil Speransky

Reputation: 30473

I saw such patch:

class String
  def is_number?
    true if Float(self) rescue false
  end
end

if (params[:paramA].blank? || !params[:paramA].is_number?)

Or without the patch:

if (params[:paramA].blank? || (false if Float(params[:paramA]) rescue true))

It supports 12, -12, 12.12, 1e-3 and so on.

Upvotes: 3

Chowlett
Chowlett

Reputation: 46675

If your parameter is for an ActiveRecord model, then you should probably use validates_numericality_of. Otherwise...

You only want integers, right? How about:

if (params[:paramA].blank? || params[:paramA] !~ /^[+-]?\d+$/)

That is, check whether the parameter consists of an optional + or -, followed by 1 or more digits, and nothing else.

Upvotes: 3

Related Questions