web-dev-qa-db-ja.com

File.open、書き込み、保存しますか?

.rbファイルを取得して、特定のディレクトリ内に別の.rbファイルを作成しようとしていますが、そのファイルは実行時に指定された内容になります。これを行うための最良の方法がRubyファイルまたはRakeファイルであるかどうかはわかりません。あなたの入力は素晴らしいでしょう。

34
CharlesJHardy

これが最良のソリューションであることが判明しました。

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
17
CharlesJHardy

ファイルの作成などの単純なスクリプトを実行するだけでよい場合は、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
44
Simone Carletti
directory = "../../directory"
File.open(File.join(directory, 'file.rb'), 'w') do |f|
  f.puts "contents"
end
23
Dogbert