File.open, write and save?

2019-02-04 01:21发布

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.

3条回答
混吃等死
2楼-- · 2019-02-04 01:55
directory = "../../directory"
File.open(File.join(directory, 'file.rb'), 'w') do |f|
  f.puts "contents"
end
查看更多
forever°为你锁心
3楼-- · 2019-02-04 02:07

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.

# 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
查看更多
Ridiculous、
4楼-- · 2019-02-04 02:12

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
查看更多
登录 后发表回答