用户以以下形式输入数字:
1-800-432-4567
800-432-4567
800.432.4566
(800)432.4567
+1(800)-432-4567
800 432 4567
我希望所有这些内容被转换成剥离特殊字符的版本,例如18004324567
。数据以String
的形式呈现,因此不需要进行字符串检查。
我的方法如下:
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
有没有更好的方法来处理这个问题?在canonical_form
方法中,可以使用正则表达式检查空格,而不需要额外的空格方法吗?如何重构或以更整洁的方式完成这项任务?
number.gsub(/\D/, '')
来删除所有非数字字符。 - sschmecknumber.gsub(/\D+/, '')
: - Tushar