How to Create a File in Ruby

How to create a file in Ruby

Use:

File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }

where your options are:

  • r - Read only. The file must exist.
  • w - Create an empty file for writing.
  • a - Append to a file.The file is created if it does not exist.
  • r+ - Open a file for update both reading and writing. The file must exist.
  • w+ - Create an empty file for both reading and writing.
  • a+ - Open a file for reading and appending. The file is created if it does not exist.

In your case, 'w' is preferable.

OR you could have:

out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close

How to write to file in Ruby?

The Ruby File class will give you the ins and outs of ::new and ::open but its parent, the IO class, gets into the depth of #read and #write.

How can I create ruby file from irb?

Using File class

File.new("variables.rb", "w")

or you can run the same touch command in irb

`touch variables.rb`

Create a Text File From a Form Server Side Ruby on Rails

This isn't really a rails specific problem. It can be tackled in plain ruby.

path = "/some/file/path.txt"
content = "data from the form"
File.open(path, "w+") do |f|
f.write(content)
end

where target is where you want the file to go, and content is whatever data you're extracting from the form.

Create a file in a specified directory

The following code checks that the directory you've passed in exists (pulling the directory from the path using File.dirname), and creates it if it does not. It then creates the file as you did before.

require 'fileutils'

def create_file(path, extension)
dir = File.dirname(path)

unless File.directory?(dir)
FileUtils.mkdir_p(dir)
end

path << ".#{extension}"
File.new(path, 'w')
end

Creating an empty file in Ruby: touch equivalent?

FileUtils.touch looks like what it does, and mirrors* the touch command:

require 'fileutils'
FileUtils.touch('file.txt')

* Unlike touch(1) you can't update mtime or atime alone. It's also missing a few other nice options.



Related Topics



Leave a reply



Submit