Related Topics
Ruby File I/O
Ruby provides a way to handle file operations. This feature allows us to interact with the files in the system. The I/O has a subclass as File class that allows us to read and write files using Ruby.
I/O modes
- "r": It is the default mode that starts in the beginning of the file.
- "r+": In this mode both reading and writing operations are done
- "w": In this mode the user can perform only the writing operation, this mode either creates a new file or truncates an existing file
- "w+": In this mode both reading and writing operations can be done. Also, this mode either creates a new file or truncates an existing file
- "a": In this mode we can only write into the file, Also if the file does not exist a new file will be created else it will append the input at the end of the file
- "A+": In this mode both read/write operations can be done into the file, Also if the file does not exist a new file will be created else it will append the input at the end of the file
Ruby opening a file
There are two ways of opening a file in ruby
new
- File.new method: Using this method we can create a new file.open
- File.open method: Using this method an object is created, and the file is assigned to the object
Note: File.open method can be associated with a block.
Difference between both the methods is that File.open method can be associated with a block while File.new method can't.
f = File.new("fileName.rb")
Or,
File.open("fileName.rb", "mode") do |f|
Ruby reading a file
There are three different methods to read a file.
To return a single line,gets
is used.
Example:
file = File.open("filename.txt", "r")
contents = file.read
puts contents
To return the whole file after the current position,read
is used.
Example:
file = File.open("filename.txt", "r")
contents = file.read
puts contents
To return file as an array of lines,readlines
is used.
Example:
File.readlines("filename.txt").each_with_index do |line, line_num|
puts "#{line_num}: #{line}"
end
Ruby renaming and deleting a file
To rename a file use the rename command.
To rename a file
File.rename("olderName.txt", "newName.txt")
To delete a file we can use the delete command.
To delete a file
File.delete("filename.txt")