English 中文(简体)
What is the shortest way to insert 2 dashes into this string with ruby?
原标题:
  • 时间:2009-11-09 18:13:44
  •  标签:
  • ruby

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?

最佳回答

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})/

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"




相关问题
Ruby parser in Java

The project I m doing is written in Java and parsers source code files. (Java src up to now). Now I d like to enable parsing Ruby code as well. Therefore I am looking for a parser in Java that parses ...

rails collection_select vs. select

collection_select and select Rails helpers: Which one should I use? I can t see a difference in both ways. Both helpers take a collection and generates options tags inside a select tag. Is there a ...

RubyCAS-Client question: Rails

I ve installed RubyCAS-Client version 2.1.0 as a plugin within a rails app. It s working, but I d like to remove the ?ticket= in the url. Is this possible?

Ordering a hash to xml: Rails

I m building an xml document from a hash. The xml attributes need to be in order. How can this be accomplished? hash.to_xml

multiple ruby extension modules under one directory

Can sources for discrete ruby extension modules live in the same directory, controlled by the same extconf.rb script? Background: I ve a project with two extension modules, foo.so and bar.so which ...

Text Editor for Ruby-on-Rails

guys which text editor is good for Rubyonrails? i m using Windows and i was using E-Texteditor but its not free n its expired now can anyone plese tell me any free texteditor? n which one is best an ...

热门标签