(Following my previous question, Ruby: how can I copy a variable without pointing to the same object? )
I am writing a simple Ruby program to make some replacements in a .svg file. The first step is to extract the information from the file and put it in an array. In order not to read the file from disk every time this function is called, I try to use the memoize template - use the cached result for each call after the first.
To do this, I use a global variable defined immediately before the function. But even if I .dup this variable for a local one, before returning the local variable, the function that calls it still modifies the global variable.
Here is my actual code:
#memoize to keep from having to read original file on each pass $svg_filedata_cache = []
Two questions (one or both answers):
- Why do other functions that accept and modify the value returned here also affect the global variable, although I used
.dup to copy it? - I'm new to Ruby, and I'm sure this is not the most Rubyesque way to do this (and I don't like global variables anyway). Can you suggest a better strategy?
ruby
Nathan Long Sep 23 '09 at 12:31 2009-09-23 12:31
source share