Aidin
Aidin

Reputation: 19

Find a text between double quotation in ruby by gsub

I wanna find a text in the text file by gsub in ruby and change it like this:

My text in main file:

set description "alas-cd002-ak"

And I wanna change it to below:

<desc>alas-cd002-ak</desc>

So I used below command but it didn't work:

text.gsub!(/\sset\sdescription\s"(?<name>^[a-zA-Z0-9_.-]*$)"/,'<desc>\k<name></desc>')

Please help me fix my gsub code. also I'm new in Ruby.

Upvotes: 1

Views: 132

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110725

The best approach is to use a regular expression, as @Wiktor has done in a comment. This is simply a demonstration of a way to use a regular expression with an enumerator.

str = "set description \"alas-cd002-ak\""

enum = ['<desc>', '</desc>'].cycle
  #=> #<Enumerator: ["<desc>", "</desc>"]:cycle> 
str.gsub('"') { enum.next }
  #=> "set description <desc>alas-cd002-ak</desc>" 

Note: puts str displays

set description "alas-cd002-ak"

Upvotes: 2

Related Questions