Ruby has two built in classes for us to work with files and folders those classes are
Dir for directories and
File for the files.
To create a Dir instance, you pass a directory path to new like the following:
d = Dir.new("/home/shaher/work/test") d.entries => ["..", ".", "file.txt", "main.rb", ".csv"]
We can also use the class method
Dir.entries("/home/shaher/work/test") => ["..", ".", "file.txt", "main.rb", ".csv"]
We can get hold of the entries using the entries method,
or using the glob technique.
And the main difference is that globbing the directory doesn’t return the hidden entries (entries whose names start with a period.)
It also permits the wildcard matching and the recursive matching in the subdirectories.
entries method we have the files in a nicely structured array so let's dive into the file class to do the work on our files.
To create the file and write value we can do the following
f = File.new("comment.txt", "w")
Now you will see the file created and we have the object to use.
Let's add some text to the file we just created and close the file
f.puts "this text meant to be added to the comment file" f.close
well we added the text but we wanna add more and update the file then we do the following
f = File.new("comment.txt", "a") f.puts "we added this extra text to update the file" f.close
Now we have our file holds the text we added and updated.
File.new to create a File object make us close the file ourselves.
Ruby as always being elegant and meant for our happiness it provides an alternate way to open files that puts
the task of closing the file in it's hands.
File.open with a code block.
When we call File.open with a block, the block receives the File object as its single argument.
So we use that File object inside the block and When the block ends, the File object is automatically closed.
In the following example our file is opened and read in line by line for processing.
File.open("comment.txt") do |f| f.each do |line| puts line.upcase end end => THIS TEXT MEANT TO BE ADDED TO THE COMMENT FILE => WE ADDED THIS EXTRA TEXT TO UPDATE THE FILE
Ruby stops iterating when it hits the end of the file and closes the file.
Another method ruby provides is
readlines which reads the whole file into an array like the example below:
File.readlines("comment.txt") do |f| f.each do |line| puts line end end => ["this text meant to be added to the comment file\n", "we added this extra text to update the file\n"]
But why all that and not just iterate on the file and avoid wasting the space required to hold the file’s contents in memory?
Along with File and Dir classes there is also FileUtils module which provides some practical and convenient methods that make it easy to manipulate files from Ruby in a concise manner and in ways that correspond to familiar system commands.
File class reference
Dir class reference
I hope you enjoyed reading this article and found it useful! 🙂