Write output to multiple files

Discussion in 'Ruby' started by Milo Thurston, Apr 23, 2009.

  1. I have encountered something I thought would be trivial but I can't
    quite get it to work properly. I have a load of data that is stored in
    various locations and need to create several files, one for each
    location, each containing the data in that location. Getting an array of
    objects containing the file name and location is easy, so I was thinking
    along the lines of this pseudocode:

    data.each do |d|
    output_filename = "#{d.location}.txt"
    if !File.exists?(output_filename)
    # create it and write d.file_name to it
    # simply write d.file_name to it
    # close all open files

    The locations of the data are numerical ids so I could expect filenames
    like 1.txt, 2.txt and so on, and I have also sorted them before
    processing so that they could be opened and filled sequentially. But, it
    is not clear to me how to properly manage the file handles so any
    suggestions would be welcome.
    Posted via http://www.ruby-forum.com/.
    Milo Thurston, Apr 23, 2009
    1. Advertising

  2. Robert Klemme wrote:

    > If I understood you properly:
    > # untested
    > last_name = nil
    > io = nil
    > begin
    > data.sort_by {|d| d.location}.each do |d|
    > output_filename = "#{d.location}.txt"
    > unless output_filename == last_name
    > io.close rescue nil
    > io = File.open(output_filename, "a")
    > end
    > io.puts d.file_name
    > ensure
    > io.close rescue nil
    > end

    Yes, that looks like just the job, thanks. I was trying something
    similar but without the begin/ensure/end block and that is presumably
    why I was having difficulty.
    Posted via http://www.ruby-forum.com/.
    Milo Thurston, Apr 23, 2009
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.

Share This Page