用户以下列形式输入数字:
- 1-800-432-4567
- 800-432-4567
- 800.432.4566
- (800)432.4567
- +1(800)-432-4567
- 800 432 4567
我希望所有这些都变成一个剥离版本,没有像18004324567这样的特殊字符.数据以字符串的形式出现,因此不需要字符串检查.
我的方法如下:
- 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方法中的正则表达式检查空格,而无需额外的空格方法吗?如何以更整洁的方式重构或完成?
解决方法
如果String的tr方法的第一个参数以^开头,那么它表示除列出的字符之外的所有字符.
- def canonical_form str
- str.tr('^0-9','')
- end