How to Create a File in Ruby

Hassan Ejaz Feb 02, 2024
How to Create a File in Ruby

We will introduce how to create a new file in Ruby using code with an example.

Create a File in Ruby

When we are working on commercial applications, there are some situations in which we wonder how to create a new file using just code in Ruby. We can create files to save the error log of applications, or we want to save some important data for backup or some other purpose.

Ruby provides a method to read, write or open new files. We can also create new files using the same method.

Ruby is a high-level programming language, and it is used for multiple purposes. Some great feature that Ruby provides is dealing with the files.

Ruby provides a File method that can be used to read or write files. We can create new files and write them as well.

Let’s go through an example and try to create a new file in Ruby using code, as shown below.

# Ruby
File.open('Errorlog.txt', 'w') { |f| f.write('New file created') }

The above command will create a new file with the name Errorlog and add a line. If we want to add more text or content to the newly created file, we can also write code on multiple lines, as shown below.

# Ruby
create_file = File.new('ErrorLog.txt', 'w')
puts 'New File Created!'
create_file.puts('New file created!')
create_file.puts('Content Added in New file!')
out_file.close
puts 'New File Closed!'

This command will create a new file and open it. It will add two lines to this file and then close the file.

Related Article - Ruby File