Ruby-on-rails File.open、写入和保存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5009031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File.open, write and save?
提问by ChuckJHardy
I am trying to get a .rb file to make another .rb file within a specific directory with specified content, when that file is run. I dont know whether the best way to do this would be with a Ruby file or a Rake file. You input would be great.
我正在尝试获取一个 .rb 文件,以便在运行该文件时在具有指定内容的特定目录中创建另一个 .rb 文件。我不知道最好的方法是使用 Ruby 文件还是 Rake 文件。你的输入会很棒。
采纳答案by ChuckJHardy
This turned out to be the best solution.
结果证明这是最好的解决方案。
File.open("linecount.txt",'w') do |filea|
File.open("testfile.txt",'r') do |fileb|
while line = fileb.gets
filea.puts line.length
end
end
end
回答by Simone Carletti
If you just need to perform a simple script like creating a file, you can simply use a Ruby script without creating a rake task.
如果您只需要执行像创建文件这样的简单脚本,您可以简单地使用 Ruby 脚本而无需创建 rake 任务。
# file origin.rb
target = "target.rb"
content = <<-RUBY
puts "I'm the target!"
RUBY
File.open(target, "w+") do |f|
f.write(content)
end
And you can execute the file with
你可以用
$ ruby origin.rb
回答by Dogbert
directory = "../../directory"
File.open(File.join(directory, 'file.rb'), 'w') do |f|
f.puts "contents"
end

