I have a loop which should assign different variable names depending on filesname which are contained in an array.
Each variable is set as an empty array.
filenames = ['file1', 'file2']
filenames.each do |filename|
"@data_" + "#{filename}" = [] # used @ as I need these variables externaly from the loop
end
This gives me the following error
syntax error, unexpected '=', expecting keyword_end
What I don’t understand is if I use
filenames.each do |filename|
p "@data_" + "#{filename}"
end
it renders correctly
@data_file1
@data_file2
And if I set an empty array through the loop
filenames.each do |filename|
@data = []
end
p @data
#=> []
it works too…
Thanks for your help!
I would recommend using a data structure rather than synthesizing instance variables1 with meta-programming.
Why not just:
Now you can just reference
@data['file1']where you want the ‘file1’ Array object.1. But for the record, here is one way: