I’m cleaning up a few phone number entries in a CSV file using Ruby. Some users have entered unwanted characters and I want to sort through and delete them all (some include: periods, parenthesis, hyphens). While writing my code, I realized I could use the .delete method provided by Ruby, like so:
def clean_num
@file.each do |line|
number = line[3]
#Would need a .delete for every unwanted character?
clean_number = number.delete(".")
puts clean_number
end
end
What’s a more efficient way to delete the other characters mentioned above?
You’re looking for regular expressions:
The first argument to
gsubis the pattern to find, the second is what to replace each occurrance with.This replaces everything that isn’t a digit (
[^\d]) with an empty string ("").