user1680893
user1680893

Reputation: 31

How do I insert characters into white spaces using Ruby

Forgive me, I am very new to Ruby and relatively new to programming in general. My problem is probably not hard, but I have googled until my fingers bled looking for a solution and I just cant get it.

I have a line of text that looks like this:

6 19 11 28 22 localhost G6UI ip0 cameraLink cameraLinkMissingScans 15116

After all is said and done, I want it to look like this:

6.19.2014,11.28.22,localhost,G6UI,ip0,cameraLink cameraLinkMissingScans 15116

I have accomplished this in Bash (I am essentially just making a CSV file, with the time and date formatted the way I want it) but, for reasons to lengthy to explain, Id like to do it with Ruby.

I have a start, although its probably a bit sad:

myLineOfText.sub!(/[^-a-zA-Z0-9]/,'\1.\2.')

Which gives me this:

6..19 11 28 22 localhost G6UI ip0 cameraLink cameraLinkMissingScans 15116

Any help would be greatly appreciated, I just need something to get me started.

Thanks in advance.

Upvotes: 0

Views: 65

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

With questions such as this one, the answer depends on what is fixed and what is variable in the data's format. I have assumed:

  • there are at least nine substrings separated with spaces
  • substrings 0 and 1 (base 0) correspond to the month and year, and are to be combined with the literal "2014" to form a date of the form dd.mm.2014
  • substrings 2-4 are to be joined with '.' and followed with ','
  • substrings 5-7 are to be joined with ',' and followed with ','
  • the remainder of the substrings are to be joined with a space

I don't think a regex is the right tool for the formating; rather just split the string on spaces and form the new string by using a series of String#join's, combining the resulting substrings in the obvious way:

s = "6 19 11 28 22 localhost G6UI ip0 cameraLink cameraLinkMissingScans 15116"
a = s.split(' ')
#=> ["6", "19", "11", "28", "22", "localhost", "G6UI", "ip0", "cameraLink",
#    "cameraLinkMissingScans", "15116"]

a[0]+'.'+a[1]+'.2014,'+a[2..4].join('.')+','+a[5..7].join(',')+','+
  a[8..-1].join(' ')
#=> "6.19.2014,11.28.22,localhost,G6UI,ip0,cameraLink cameraLinkMissingScans 15116"

Upvotes: 0

arco444
arco444

Reputation: 22821

If you can be sure the format always remains the same, you can do:

str.sub!(/(\d+) (\d+) (\d+)/,'\1.\2.\3').gsub!(/ /,',')

Example:

str='6 19 11 28 22 localhost G6UI ip0 cameraLink cameraLinkMissingScans 15116'
str.sub!(/(\d+) (\d+) (\d+)/,'\1.\2.\3').gsub!(/ /,',')
puts str
=> "6.19.11,28,22,localhost,G6UI,ip0,cameraLink,cameraLinkMissingScans,15116"

Upvotes: 1

Related Questions