用户以下列形式输入数字:
1-800-432-4567
800-432-4567
800.432.4566
(800)432.4567
+1(800)-432-4567
800 432 4567
Run Code Online (Sandbox Code Playgroud)
我希望所有这些都变成一个没有特殊字符的剥离版本18004324567.数据以a的形式出现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
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?可以使用canonical_form方法中的正则表达式执行空格检查而无需额外的空格方法吗?如何以更简洁的方式对其进行重构或完成?
ste*_*lag 31
如果trString方法的第一个参数以^,则表示除列出的字符之外的所有字符.
def canonical_form str
str.tr('^0-9', '')
end
Run Code Online (Sandbox Code Playgroud)
Mat*_*t H 19
上面的几个解决方案 - 我对一些人感兴趣的基准测试:
str = "1-800-432-4567"
Benchmark.ms { 10000.times{str.scan(/\d/).join} }
#=> 69.4419999490492
Benchmark.ms { 10000.times{str.delete('^0-9')} }
#=> 7.574999995995313
Benchmark.ms { 10000.times{str.tr('^0-9', '')} }
#=> 7.642999989911914
Benchmark.ms { 10000.times{str.gsub(/\D+/, '')} }
#=> 28.084999998100102
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6055 次 |
| 最近记录: |