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
How to Create a Deep Copy of an Object in Ruby
Is There a "Do ... While" Loop in Ruby
What Is the Best Method of Handling Currency/Money
Get the Name of the Currently Executing Method
Difference Between Class Variables and Class Instance Variables
Trying to Learn/Understand Ruby Setter and Getter Methods
Difference Between \A \Z and ^ $ in Ruby Regular Expressions
Ruby: What Does 'Require: False' in Gemfile Mean
Sudo Gem Install' or 'Gem Install' and Gem Locations
What's the Difference Between Ruby'S Dup and Clone Methods
What Are All the Common Ways to Read a File in Ruby
How to Create Multiple Submit Buttons For the Same Form in Rails
Connecting Rails 3.1 With Multiple Databases
Spawn a Background Process in Ruby