37

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

4

3 回答 3

45

如果您只需要执行一个简单的脚本(例如创建文件),则可以简单地使用 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
于 2011-02-15T20:29:26.770 回答
24
directory = "../../directory"
File.open(File.join(directory, 'file.rb'), 'w') do |f|
  f.puts "contents"
end
于 2011-02-15T20:22:44.933 回答
19

事实证明这是最好的解决方案。

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
于 2011-02-28T07:54:02.767 回答