Ruby - Read whole text file to memory

Introduction

Read whole text file to memory

Demo

lines = File.readlines("main.rb") 
line_count = lines.size #  ww w  .j  av  a2s  . c  o m
text = lines.join 

puts "#{line_count} lines"

Result

File readlines method reads an entire file into an array, line by line.

You can use this both to count the lines and join them all into a single string.

Related Topic