rails strip non numeric values before save
You certainly have defined the phonenumber
column as number. That's why when you set '925-555-5555'
in the phonenumber
attribute, it is casted to a number, and only 925
is kept.
The best solution is to change the type of the column in your database to string
. Create a new migration:
change_column :table_name, :phonenumber, :string, limit: 30
Otherwise, you can override the setter like this to remove the non numeric characters (but it won't fix phone numbers starting with '0's):
def phonenumber=(phonenumber)
write_attribute(:phonenumber, phonenumber.gsub(/\D/, ''))
end
More alternatives in this blog post
How to remove all non-digits from a string in ruby?
If the first argument of the tr
method of String starts with ^
, then it denotes all characters except those listed.
def canonical_form str
str.tr('^0-9', '')
end
Strip all characters except digits in Rails
class YourModel < ActiveRecord::Base
before_validation :tweak_my_attribute
def tweak_my_attribute
self.my_attribute = my_attribute.to_s.gsub(/\D/, '')
end
end
Gsub for non-numeric characters is removing numeric characters as well
Here is the answer:
gsub
will return the original string if it doesn't match anything. On the other hand, gsub!
will return nil
in such case.
If both methods match, they will return the string with the substitutions in place and there is nothing special about it, except that gsub!
will modify the receiver object as you should already know.
Here are some examples that illustrate the facts. Pay special attention to the subjects and the returned values. You can try the following in irb if you want.
phone_number = "888-555-0110" #=> "888-555-0110"
stripped_pn = phone_number.gsub(/\D/, '') #=> "8885550110"
phone_number #=> "888-555-0110"
stripped_pn.gsub(/\D/, '') #=> "8885550110"
Here are the same examples with gsub!
:
phone_number = "888-555-0110" #=> "888-555-0110"
stripped_pn = phone_number.gsub!(/\D/, '') #=> "8885550110"
phone_number #=> "8885550110"
stripped_pn.gsub!(/\D/, '') #=> nil
Stripping Phone Numbers of Non-numeric Values During SQL Query in Rails
If you'd just like to limit your effort to the Rails query (instead of properly formatting the phone numbers in another field in the database) here's how you could use your DB engine's REGEXP capabilities
Restaurant.where(["REGEXP_REPLACE(contact_phone, '[^[:digit:]]', '') = ?", formatted_phone]).each do |r|
#irrelevant code here
end
Ruby removing non numeric values from array and converting rest to float
The problem is you're mutating freq only in the then
condition and not in the else condition.
There are enumerable methods that mutate for you, they usually end with a !
:
freq = ["1", "2", "3b", "c3", "4", "", "5t"]
=> ["1", "2", "3b", "c3", "4", "", "5t"]
freq.reject! { |minutes| minutes.match(/\D/) || minutes == "" }.map! { |minutes| minutes.to_f }
=> [1.0, 2.0, 4.0]
Rails strip all except numbers commas and decimal points
Try:
rate = rate.gsub(/[^0-9,\.]/, '')
Basically, you know the ^
means not when inside the character class brackets [] which you are using, and then you can just add the comma to the list. The decimal needs to be escaped with a backslash because in regular expressions they are a special character that means "match anything".
Also, be aware of whether you are using gsub
or gsub!
gsub!
has the bang, so it edits the instance of the string you're passing in, rather than returning another one.
So if using gsub!
it would be:
rate.gsub!(/[^0-9,\.]/, '')
And rate
would be altered.
If you do not want to alter the original variable, then you can use the version without the bang (and assign it to a different var):
cleaned_rate = rate.gsub!(/[^0-9,\.]/, '')
I'd just google for tutorials. I haven't used one. Regexes are a LOT of time and trial and error (and table-flipping).
This is a cool tool to use with a mini cheat-sheet on it for ruby that allows you to quickly edit and test your expression:
http://rubular.com/
Strip Phone Number Input Before Validation in Rails
Using an integer column type is problematic because Rails performs type casting on assignment (and retrieval from) database-backed attributes. This means that, when you try to assign a string to an integer field, you'll typecast the string and lose the data. For example:
"123-123-1234".to_i # => 123
So that's why you have undefined method 'gsub' for 646:Fixnum
. Rails has already typecast the phone number string entered by the user, truncated the value to 646, and, yes, gsub
is not a valid method for Fixnum. So definitely change the phone number column type to String. Then you'll be free to perform your gsub and the phone number won't be truncated beforehand.
def strip_contact_phone
self.contact_phone.gsub!(/[^0-9]/, '')
end
How do I strip non alphanumeric characters from a string and keep spaces?
Add spaces to the negated character group:
@search_query = @search_query.gsub(/[^0-9a-z ]/i, '')
Related Topics
Iconv Deprecation Warning with Ruby 1.9.3
Uninitialized Constant Rake::Dsl in Ruby Gem
Writing Over Previously Output Lines in the Command Prompt with Ruby
Repairing Postgresql After Upgrade to Osx Mavericks
Ruby - Determine If a Number Is a Prime
How to Set the Default String Encoding on Ruby 1.9
What Does the Fail Keyword Do in Ruby
What Does "Wrong Number of Arguments (1 for 0)" Mean in Ruby
Custom Ruby Gem in Gemfile on Heroku
Undef - Why Would You Want to Undefine a Method in Ruby
Ruby 2.0 How to Uninclude a Module Out from a Module After Including It
Rails 3.1 with Postgresql: Group by Must Be Used in an Aggregate Function