What is the shortest way to insert two dashes in this ruby ​​line?

Here's the line: 04046955104021109

I need it to be formatted like this: 040469551-0402-1109

What is the shortest / most efficient way to do this with ruby?

+4
source share
4 answers

Two simple inserts will work just fine:

example_string.insert(-9, '-').insert(-5, '-') 

Negative numbers mean that you are calculating from the end of the line. You can also count from the start if you want:

 example_string.insert(9, '-').insert(14, '-') 
+15
source

What about

 s = "04046955104021109" "#{s[0,9]}-#{s[9,4]}-#{s[13, 4]}" 
+5
source

Here's a little script to show a match:

 pattern = /\A(\d*?)(\d{4})(\d{4})\Z/ s = "04046955104021109" output = s.gsub(pattern,'\1-\2-\3') 
+2
source

Sometimes I think that Regexp is overused, and in fact I kind of like a Harpastum solution, but for the record ...

 >> s = '04046955104021109' >> s.sub /(....)(....)$/, '-\1-\2' => "040469551-0402-1109" 
+1
source

All Articles