2011-02-15 60 views
27

我試圖讓一個.rb文件在指定內容的特定目錄下創建另一個.rb文件,當該文件運行時。我不知道是否最好的方法是使用Ruby文件或Rake文件。你輸入會很好。File.open,寫入並保存?

回答

12

事實證明,這是最好的解決辦法執行該文件。

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 
22
directory = "../../directory" 
File.open(File.join(directory, 'file.rb'), 'w') do |f| 
    f.puts "contents" 
end 
+0

感謝Dogbert - 如果我有更復雜的內容,比如一些常量可以放在一個字符串中的方法,我該如何去做。 – CharlesJHardy 2011-02-15 20:45:03

+0

你有什麼格式的內容?你如何獲取/生成內容? – Dogbert 2011-02-15 23:24:22

+0

我應該在哪寫這段代碼? – 2015-07-26 14:23:01

39

如果您只是需要執行一個簡單的腳本來創建文件,那麼您可以簡單地使用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 
相關問題