Adam Lee
Adam Lee

Reputation: 3003

Inserting a string after a certain character in Ruby

I have to insert a string after a certain character using Ruby.

For example, if I have a line like the following:

(N D CGYRWIFGD2S7 0 1 N)(N D CGYCGYOVFBK0 0 N N)(ISA N N N CGYCG3FEXOIS N PUB NONE N N 0)(ISA N N N CGYCGYFGAOIS N PUB NONE N N 0)(ISA N N N CGYCG2FGAOIS N PUB NONE N N 0)(N D CGYCGYOVFBK1 0 N N)(N D CGYLOCFGA2S7 0 N N)(N D CGY01TFGD2S7 0 N N)(N D CGY01TCASUAL 0 N N)(N D CGYATTUSAOS7 0 1 N)(ISA N N N CGYAGTAD4OIS N PUB NONE 0 N 7)

I'd like to insert the html tag <br /> after every closing bracket ")".

I guess I can use regex, but every line has different number of brackets. So this particular line can have 5, while other line can have 20. With my limited knowledge of Ruby or in programming in general, I am seeking for help :)

Thanks!

Upvotes: 3

Views: 4611

Answers (3)

glenn jackman
glenn jackman

Reputation: 246807

Or, use split and join:

delim = ')'
s.split(delim).join(delim + '<br />')

Upvotes: 0

Sinan Taifour
Sinan Taifour

Reputation: 10795

Use gsub to globally replace.

my_string.gsub(/\)/, ")<br />");

Upvotes: 8

Duncan Beevers
Duncan Beevers

Reputation: 1820

s.gsub(')', ')<br />')

Upvotes: 16

Related Questions