Ruby - Read whole text file to memory

Introduction

Read whole text file to memory

Demo

lines = File.readlines("main.rb") 
line_count = lines.size # from w w w  . j a  v  a 2s.  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