Ruby Files Flashcards
File
A File represents digital information that exists on durable storage.
File.new
create a file in Ruby
irb :001 > my_file = File.new(“simple_file.txt”, “w+”)
=> #
irb :002 > my_file.close
In the above example, we created a new file with name simple_file.txt and mode w+ for read and write access to the file.
On the second line, we are closing the file. We want to always close files.
.close
Close a file.
File.open
We open an existing file using File.open
We will pass the file name and a second argument which will decide how the file will be opened. Usually, the following are used:
r: read-only (starts at beginning of file)
w: write-only (if the file exists, overwrites everything in the file)
w+: read and write (if the file exists, overwrites everything in the file)
a+: read-write (if file exists, starts at end of file. Otherwise creates a new file). Suitable for updating files.
Open File For Reading
File.read(“file_name”) - Spits out entire contents of the file.
File.readlines(“file_name”) - Reads the entire file based on individual lines and returns those lines in an array.
Open File For Writing
File.open(“simple_file.txt”, “w”) { |file| file.write(“adding first line of text”) }
We first open the file with the w option and invoke a block that writes the contents we specify to the file. This way of doing things makes sure the file closes at the end of the block.
Alternatively, we could open the file, write to it and finally close it. Let’s see how that works with puts:
irb :001 > sample = File.open(“simple_file.txt”, “w+”)
=> #
irb :002 > sample.puts(“another example of writing to a file.”)
=> nil
irb :003 > sample.close
=> nil
irb :004 > File.read(“simple_file.txt”)
=> “another example of writing to a file.\n”
File.delete
delete a file
irb :001 > File.new(“dummy_file.txt”, “w+”)
=> #
irb :002 > File.delete(“dummy_file.txt”)
=> 1