1

I am trying to write to a file inside a subdirectory. This file is created by the code but, once the file is created, it is empty after the script finishes its execution. What am I doing wrong?

# Creating output files print "Creating output files and filling root menu..." FileUtils.cd(outdir) do file = File.new("directory.xml", "w") file.puts "<?php header(\"Content-type: text/xml\"); ?>" file.puts "<CiscoIPPhoneMenu>" file.puts "<Title>Telefonbuch</Title>" file.puts "<Prompt>Dir External</Prompt>" letters_used.each do |letter| filename = "contacts_" + letter + ".xml" FileUtils.touch(filename) file.puts "<MenuItem>" file.puts "<Name>" + letter.upcase + "</Name>" file.puts "<URL>http://" + HOSTNAME + WEBSERV_DIR + "/" + filename + "</URL>" file.puts "</MenuItem>" end file.puts "</CiscoIPPhoneMenu>" file.rewind end print "Done\n" 

"directory.xml" should link to each "contacts_letter.xml" file, which is created by the script too, however directory.xml is empty. Why?

4
  • 3
    try replacing file.rewind with file.close Commented Dec 21, 2012 at 14:30
  • 1
    Yes, I was just writing the same comment... I was unable to recreate the issue though. You should be closing the file in either case but, if that doesn't fix it please list your OS and ruby version. Commented Dec 21, 2012 at 14:33
  • You could also add a file.flush before closing/rewinding the file Commented Dec 21, 2012 at 14:55
  • 1
    @TheConstructor close flushes automatically - ruby-doc.org/core-1.9.3/IO.html#method-i-close Commented Dec 21, 2012 at 15:23

1 Answer 1

4

Idiomatic Ruby would write to the file using a block:

File.new("directory.xml", "w") do |fo| fo.puts "<?php header(\"Content-type: text/xml\"); ?>" fo.puts "<CiscoIPPhoneMenu>" fo.puts "<Title>Telefonbuch</Title>" fo.puts "<Prompt>Dir External</Prompt>" letters_used.each do |letter| filename = "contacts_" + letter + ".xml" FileUtils.touch(filename) fo.puts "<MenuItem>" fo.puts "<Name>" + letter.upcase + "</Name>" fo.puts "<URL>http://" + HOSTNAME + WEBSERV_DIR + "/" + filename + "</URL>" fo.puts "</MenuItem>" end fo.puts "</CiscoIPPhoneMenu>" end 

This closes the file automatically at the end of the block.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the block solution was helpful, then.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.