gsub! Is modifying unspecified strings
I'm extracting some information from an XML file, and I want to perform some modifications on the data while keeping a copy of the original in a variable "origFile". This is what I have:
require "rexml/document"
include REXML
doc = Document.new File.new(thePath)
root = doc.root
array = []
root.elements.each("dict/string") {|element| array << element}
origFile = []
root.elements.each("dict"){|i| origFile << i}
theBody = array[6][0].t开发者_StackOverflow中文版o_s
theBody.gsub!(/\<!-- more --\>/, "----------Read More----------")
The problem is that after I perform gsub! on theBody, origFile also has the modification. I don't understand why this would be or how to fix it. I would really appreciate your help.
Just this:
theBody = array[6][0].to_s.dup
Without the .dup
, both of your variables are referring to the same string. With it, theBody gets a separate copy.
You are modifying the string in place, which means that you are also modifying any other reference to that string. If you only want theBody
to be modified, use dup
to copy the string and create a new instance of it:
theBody = array[6][0].to_s.dup
theBody.gsub!(/\<!-- more --\>/, "----------Read More----------")
You could also just use gsub
(without the !
):
theBody = array[6][0].to_s
theBody = theBody.gsub(/\<!-- more --\>/, "----------Read More----------")
I would recommend this:
theBody = array[6][0].to_s.
gsub(/\<!-- more --\>/, "----------Read More----------")
精彩评论