Simplicity
Simplicity

Reputation: 48946

Find and replace

I have a text file that contains file paths as follows:

http://www.accessdata.fda.gov/drugsatfda_docs/labe...

I want to replace the string "drug" by "med" wherever it occurs.

I used something like the following:

gsub!(/(drug)/,'medication') if contents.include? 'drug'

(/(drug)/ is supposed to be a regular expression, but, I may be writing it wrongly.

Do you know what I can do to perform such task?

Upvotes: 0

Views: 51

Answers (3)

orde
orde

Reputation: 5283

Your code snippet works correctly (although--as @Ryan Rebo points out--the if statement modifier isn't needed).

One note: by wrapping the string "drug" in parenthesis, that creates a capture group. The replaced string is placed into a global variable.

str = "drug"
str.gsub!(/(drug)/,'medication')
puts str #=> medication
puts $1  #=> drug

Upvotes: 0

Ryan Rebo
Ryan Rebo

Reputation: 1318

Assuming you are converting your text file to a string:

contents.gsub!(/drug/, 'medication')

will do the trick. No need for if contents.include?

Upvotes: 0

davidrac
davidrac

Reputation: 10738

I'd use content.gsub /drug/, 'medication'

Upvotes: 1

Related Questions