What is the shortest way to insert 2 dashes into this string with ruby?
Here's the string: 04046955104021109
I need it to be formatted like so: 040469551-0402-1109
What's the shortest/mos开发者_开发知识库t efficient way to do that with ruby?
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, '-')
how about
s = "04046955104021109"
"#{s[0,9]}-#{s[9,4]}-#{s[13, 4]}"
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')
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"
精彩评论