tags:

views:

29

answers:

2

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].to_s

theBody.gsub!(/\&lt;!-- more --\&gt;/, "----------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.

+1  A: 

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.

glenn mcdonald
Wow, that's great! Thanks so much!
+1  A: 

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!(/\&lt;!-- more --\&gt;/, "----------Read More----------")

You could also just use gsub (without the !):

theBody = array[6][0].to_s
theBody = theBody.gsub(/\&lt;!-- more --\&gt;/, "----------Read More----------")

I would recommend this:

theBody = array[6][0].to_s.
  gsub(/\&lt;!-- more --\&gt;/, "----------Read More----------")
Adrian