Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all non-digits from a string in ruby?

Tags:

ruby

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?

like image 450
mhaseeb Avatar asked Feb 24 '16 13:02

mhaseeb


People also ask

How do I remove non digits from a string?

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.

How do I remove numbers from a string in Ruby?

string. gsub!( /\d+/,"") will remove all numbers from the string.

How do you remove something from a string in Ruby?

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.

What is TR in Ruby?

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.


1 Answers

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 
like image 150
steenslag Avatar answered Sep 30 '22 17:09

steenslag