Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the shortest way to insert 2 dashes into this string with ruby?

Tags:

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?

like image 232
Shpigford Avatar asked Nov 09 '09 18:11

Shpigford


People also ask

What does \n do in Ruby?

A \n becomes a newline. In single quoted strings however, escape sequences are escaped and return their literal definition. A \n remains a \n .

How do you input a string in Ruby?

In Ruby, user input is made possible by the #gets method. During the executing of a Ruby program, when a line with the #gets method is read, the terminal is primed for input from the user. The input is returned as a string type after the #gets method is finished. puts "My name is #{name}!"

How do I find a dash in a string?

You can check the count of dashes in a string with: if str. Count(x => x == '-') !=


1 Answers

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, '-')
like image 190
Harpastum Avatar answered Nov 04 '22 15:11

Harpastum