这里奇怪的观察:
2.0.0-p353 :016 > "1,056".gsub!(/,/,'').to_i
=> 1056
2.0.0-p353 :017 > "955".gsub!(/,/,'').to_i
=> 0
有没有办法在不打破不在其中,
字段的数字的情况下始终如一地执行此操作?
答案 0 :(得分:1)
我认为要求是:
一种方法如下:
str = "955"
str.tap { |s| s.delete!(',') }.to_i
#=> 955
str
#=> "955"
str = "1,955"
str.tap { |s| s.delete!(',') }.to_i
#=> 1955
str
#=> "1955"
str = "1,955,658"
str.tap { |s| s.delete!(',') }.to_i
#=> 1955658
str
#=> "1955658"
答案 1 :(得分:1)
叹息......基准人......
require 'fruity'
NUM = '1,234,567,890'
compare do
_delete { NUM.delete(',').to_i }
_gsub { NUM.gsub(',', '').to_i }
_scan {NUM.scan(/\d+/).join.to_i }
_split { NUM.split(',').join.to_i }
end
# >> Running each test 4096 times. Test will take about 1 second.
# >> _delete is faster than _split by 2.4x ± 0.1
# >> _split is faster than _gsub by 10.000000000000009% ± 1.0%
# >> _gsub is faster than _scan by 2.2x ± 0.1
换句话说,使用delete(',')
删除分隔逗号,然后将结果字符串转换为整数。不要将其拆分为数组,然后重新加入,不要将其扫描到数组中,不要让gsub
将','
转换为正则表达式,然后将所有匹配项替换为{{1 }}