Ruby Files Flashcards

1
Q

File

A

A File represents digital information that exists on durable storage.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

File.new

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

.close

A

Close a file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

File.open

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Open File For Reading

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Open File For Writing

A

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”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

File.delete

A

delete a file

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly