Ruby - Output text file line by line

Introduction

If text.txt is in the current directory, the result is the entire text file.

Demo

File.open("main.rb").each { |line| puts line }

Result

Edit the code to the follows:

Demo

line_count = 0 
File.open("main.rb").each { |line| line_count += 1 } 
puts line_count

Result

Here, you initialize line_count to store the line count.

Then open the file and iterate over each line while incrementing line_count by 1 each time.

When you're done, you print the total to the screen.

Related Topics