so i've written code iterates through several hundred csv files, , stores last element of each new array.
module example @array = [] def example(file_names) #where file_names array of strings csv files file_names.each { |x| @array << (csv.parse open("#{x}.csv").read)[-1] if file.exists?("{x}.csv") == true } return @array end end
executing code can take time, , want able refer newly-created array in other methods without having run code again. there way permanently store @array variable?
it depends on how permanent want results be. if don't want parse csv files lifetime of program, can cache result in member variable (as @array), , execute code if array empty example:
module example def example(file_names) # ||= calculate result if @array nil, otherwise # return saved value @array ||= file_names.map { |x| csv.parse open("#{x}.csv").read)[-1] if file.exists?("{x}.csv") } end end
if want work saved in-between executions of program can try saving results (single) file , reading in, using perhaps on of following:
- json: http://ruby-doc.org/stdlib-2.2.2/libdoc/json/rdoc/json.html
- yaml: http://ruby-doc.org/stdlib-2.2.2/libdoc/yaml/rdoc/yaml.html
- marshal: http://ruby-doc.org/core-2.2.2/marshal.html
- see mu-is-too-short's comment of drawbacks of using marshal