ruby can be used to read files. You can either read a file directly into a string variable or read a file line by line.

These functionality ruby provides out of the box is for read files on the hard disk, not on the cloud.

Download Free Ruby Ebook

Read files in ruby

Read file

The ruby program below reads a file from the disk. ruby will read the file from the same directory as your program. If the file is in another directory, specify its path.

If you want to read a file at once, you can use:

1
2
3
4
#!/usr/bin/ruby

content = File.read("read.rb")
puts content

This reads the entire file into a ruby string.

Line by line

If you want to read a file line by line, into an array, you can use this code:

1
2
3
4
5
6
7
8
#!/usr/bin/ruby

lines = File.readlines('read2.rb')
puts lines

# It's an array so we can access elements
puts lines[0]
puts lines[1]

Exercises

  1. Think of when you’d read a file ‘line by line’ vs ‘at once’?
  2. Create a new file containing names and read it into an array