1

我正在尝试写入子目录中的文件。该文件由代码创建,但是一旦创建文件,脚本完成执行后它就为空。我究竟做错了什么?

# 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”应该链接到每个由脚本创建的“contacts_letter.xml”文件,但是 directory.xml 是空的。为什么?

4

1 回答 1

4

惯用的 Ruby 将使用块写入文件:

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

这会在块的末尾自动关闭文件。

于 2012-12-21T14:59:46.347 回答