Arv Vyas
Arv Vyas

Reputation: 9

string and numeric separation

I did post the phone no from form

def update_phone
  if params[:phone]
  #here I want to check weather params[:phone] is number or string 
end

I did use params[:phone].class it is always showing string class. How I can find whether string or integer?

Upvotes: 0

Views: 106

Answers (3)

Hauleth
Hauleth

Reputation: 23556

In Ruby you mostly do not operate on types but on behaviour of variable. If you want to chceck that params[:phone] is valid phone number use regexp, i. e.:

phone = params[:phone] if params[:phone] =~ /\A\(?\d{3}\)?-?\d{3}-?\d{3}\Z/

But even better option is to check this in validators in your model.

Upvotes: 1

davidrac
davidrac

Reputation: 10738

edited, thanks for the comment. I figure this works for most common cases. however, this won't work with leading zeros:

str = params[:phone]

#it is numeric if the following is true:
str.to_f.to_s == str || str.to_i.to_s == str

Upvotes: 0

arnep
arnep

Reputation: 6241

Your should use some Validators in your model combined with a regex for phone numbers: depending on your country's phone number system only digits and some formatting characters like +-./() and space should be allowed: +23 (0) 322/242324-12 or 234.1432.123 are both valid numbers.

Upvotes: 0

Related Questions