Search code examples
rubyvariablesdynamic-variables

Dynamic variable from string in Ruby


I am copying each line of a file to separate files, depending on the content. Each line begins with "foo" or "bar", and I want to read the first few characters of each line and dynamically change the file name variable.

readfile = File.open("myfile.txt", 'r')
file_foo = File.open("file1.txt", 'w')
file_bar = File.open("file2.txt", 'w')

for line in readfile
  writefile = 'file_' + line[0..2]
  writefile.write(line)
end
file_foo.close
file_bar.close

This throws an error, as the variable writefile refers to the string "file_foo" or "file_bar".

Suggestions for an elegant Rubyist solution? I couldn't see from the documentation how send method could be applied here if that is indeed the way to go.


Solution

  • Make a hash of files:

    readfile = File.open("myfile.txt", 'r')
    
    files = {
      'foo' => File.open("file1.txt", 'w'),
      'bar' => File.open("file2.txt", 'w')
    }
    
    for line in readfile
      files[line[0..2]].write(line)
    end
    files.each {|k, v| v.close}