(Follow-up to my earlier question, Ruby: how can I copy a variable without pointing to the same object?)
I'm writing a simple Ruby program to make some substitutions in an .svg file. The first step is to pull information from the file and put it in an array. In order to keep from reading the file from disk every time this function is called, I'm trying to use the memoize design pattern - use a cached result on every call after the first one.
To do this, I'm using a global variable, defined just before the function. But even though I .dup
that variable to a local one before returning the local variable, the function that calls this one is still modifying the global variable.
Here is my actual code:
#memoize to keep from having to read original file on each pass
$svg_filedata_cache = [] #the global variable
def svg_filedata(filename)
if $svg_filedata_cache.empty?
File.open(filename, "r"){|f| $svg_filedata_cache = f.readlines}
end
svg_filedata_cache = $svg_filedata_cache.dup #try to copy it
return svg_filedata_cache #SHOULD point to a different object (but doesn't)
end
Two questions (answer either or both):
- Why do other functions, which take in and modify the value returned here, also affect the global variable, even though I used
.dup
to copy it? - I'm new to Ruby and I'm sure this isn't the most Rubyesque way to do this (and I don't like global variables, anyway). Can you suggest a better strategy?