tags:

views:

91

answers:

5

Here's the string: 04046955104021109

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

What's the shortest/most efficient way to do that with ruby?

+4  A: 

how about

s = "04046955104021109"
"#{s[0,9]}-#{s[9,4]}-#{s[13, 4]}"
nicholaides
+7  A: 

Two simple inserts will work just fine:

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

The negative numbers mean that you are counting from the end of the string. You could also count from the beginning if you'd like:

example_string.insert(9, '-').insert(14, '-')
Harpastum
+2  A: 

Here's a little script to show the match:

pattern = /\A(\d*?)(\d{4})(\d{4})\Z/

s = "04046955104021109"

output = s.gsub(pattern,'\1-\2-\3')
Ben
+1  A: 

Sometimes I think Regexp's are overused, and actually I kind of like Harpastum's solution, but for the record...

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

ops -..- sorry it was wrong answer.

marocchino
So, why don't you delete it?
glenn jackman
i try it. but delete button doesn't works.
marocchino