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.
"#{fileNameFromUser}"
is same asfileNameFromUser.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; sofileNameFromUser
should suffice, no?12
initially and the replacements are1 => 2
and2 => 3
, should the final result be23
or33
?