Ruby Files Flashcards Preview

Ruby - Launch School - Introduction to Programming > Ruby Files > Flashcards

Flashcards in Ruby Files Deck (7):


A File represents digital information that exists on durable storage.


create a file in Ruby

irb :001 > my_file ="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 a file.


We open an existing file using

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_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"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 ="simple_file.txt", "w+")
=> #
irb :002 > sample.puts("another example of writing to a file.")
=> nil
irb :003 > sample.close
=> nil
irb :004 >"simple_file.txt")
=> "another example of writing to a file.\n"



delete a file

irb :001 >"dummy_file.txt", "w+")
=> #
irb :002 > File.delete("dummy_file.txt")
=> 1