Ruby:写入子目录中的文件

时间:2012-12-21 14:17:59

标签: ruby file

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

# 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为空。为什么呢?

1 个答案:

答案 0 :(得分:3)

惯用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

这会在块结束时自动关闭文件。