开发者

Ruby string manipulation of numbers

开发者 https://www.devze.com 2023-03-30 00:19 出处:网络
I have example this number: 5032 I want to get this: 5.0.32 How can I do this with ruby string开发者_如何转开发 manipulation? I\'d be curious to hear the pros and cons of these different solutions.

I have example this number: 5032

I want to get this: 5.0.32

How can I do this with ruby string开发者_如何转开发 manipulation?


I'd be curious to hear the pros and cons of these different solutions. What's the fastest ? What's the clearest ? Are regular expressions expensive ?

Here's yet another solution:

sprintf("%s.%s.%s%s", *5032.to_s.split(""))

Here's our results. Mine is slowest:

require 'benchmark'

n = 500000
Benchmark.bm do |x|
  x.report { n.times {"5032".sub(/^(.)(.)/,"\\1.\\2.")}}
  x.report { n.times {"5032".insert(2, ".").insert(1, ".")}}
  x.report { n.times {sprintf("%s.%s.%s%s", *5032.to_s.split("")) }}
end



     user     system      total        real
  0.610000   0.000000   0.610000 (  0.607663)
  0.320000   0.000000   0.320000 (  0.325050)
  3.030000   0.000000   3.030000 (  3.029342)


Your question is a little bit vague but you can do this:

number = "5032"
number = "5032".insert(2, ".").insert(1, ".")
puts number

See the API doc for insert here.


> 5032.to_s.sub(/^(.)(.)/,"\\1.\\2.")
=> "5.0.32"
0

精彩评论

暂无评论...
验证码 换一张
取 消