0

I'm having a bit of trouble searching through a file and editing certain parameters of the file. The code is below

file_names = ["#{fileNameFromUser}"]

file_names.each do |file_name|
 text = File.read(file_name)
 replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}")
 replacedcontent += text.gsub(/textToReplace2/, "#{ReplaceWithThis2}")

# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts replacedcontent}
end

so right now what it does is that it print the contents of the file twice and I can only assume its because its inside the do loop. My end goal here is that the file has textToReplace and textToReplace2 and I need it to read through the file, replaced both with whatever the user inputs and save/write changes to the file.

2
  • 1
    "#{fileNameFromUser}" is same as fileNameFromUser.clone, but the latter is easier to read. But I see no need in your code for cloning, since the strings are not being mutated; so fileNameFromUser should suffice, no?
    – Amadan
    Commented Aug 13, 2018 at 12:40
  • 1
    If the file contains 12 initially and the replacements are 1 => 2 and 2 => 3, should the final result be 23 or 33?
    – Stefan
    Commented Aug 13, 2018 at 13:10

2 Answers 2

2

it print the contents of the file twice and I can only assume its because its inside the do loop

Nope, it's because you append it twice:

text = first_replacement_result
text += second_replacement_result

There's two ways to do this: one with mutation:

text.gsub!(...) # first replacement that changes `text`
text.gsub!(...) # second replacement that changes `text` again

or chained replacement:

replacedcontent = text.gsub(...).gsub(...) # two replacements one after another        
1

You will need to re-use replacedcontent instead of concatenating it to avoid printing it twice.

file_names = ["#{fileNameFromUser}"]

file_names.each do |file_name|
text = File.read(file_name)
replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}")
replacedcontent = replacedcontent.gsub(/textToReplace2/, "#{ReplaceWithThis2}")

# To write changes to the file, use:
File.open(file_name, "w") {|file| file.puts replacedcontent}
end

OR

replacedcontent = text.gsub(/textToReplace/, "#{ReplaceWithThis}").gsub(/textToReplace2/, "#{ReplaceWithThis2}")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.