Users input numbers in the following forms:
1-800-432-4567 800-432-4567 800.432.4566 (800)432.4567 +1(800)-432-4567 800 432 4567
I want all of these to be turned into a stripped version without the special characters like 18004324567
. The data come in the form of a String
, so string checking isn't required.
My method is as below:
def canonical_form number a = remove_whitespaces number #to clear all whitespaces in between a.gsub(/[()-+.]/,'') end def remove_whitespaces number number.gsub(/\s+/,'') #removes all whitespaces end
Is there a better way to do this? Can the white space check with the regular expression in canonical_form
method be performed without having an extra method for white spaces? How can this be refactored or done in a neater way?
In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.
string. gsub!( /\d+/,"") will remove all numbers from the string.
In Ruby, we can permanently delete characters from a string by using the string. delete method. It returns a new string with the specified characters removed.
The tr() is an inbuilt method in Ruby returns the trace i.e., sum of diagonal elements of the matrix. Syntax: mat1.tr() Parameters: The function needs the matrix whose trace is to be returned. Return Value: It returns the trace.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With