File.open,写和保存?

时间:2011-02-15 20:18:45

标签: ruby-on-rails ruby rake rakefile

我正在尝试获取.rb文件,以便在运行该文件时在指定内容的特定目录中生成另一个.rb文件。我不知道最好的方法是使用Ruby文件还是Rake文件。你的输入会很棒。

3 个答案:

答案 0 :(得分:42)

如果您只需要执行一个简单的脚本,例如创建文件,您只需使用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

您可以使用

执行该文件
$ ruby origin.rb

答案 1 :(得分:23)

directory = "../../directory"
File.open(File.join(directory, 'file.rb'), 'w') do |f|
  f.puts "contents"
end

答案 2 :(得分:17)

这是最好的解决方案。

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