How to read a file line by line in Ruby?

Member

by natalia , in category: Ruby , 2 years ago

How to read a file line by line in Ruby?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@natalia You can use File.readline() in Ruby to ready any file line by line and below is code:


1
2
3
4
file_path = '/tmp/test.txt'
File.readlines(file_path).each do |line|
  puts(line)
end


by santina.kub , a year ago

@natalia 

You can read a file line by line in Ruby using the "each_line" method.


Here's an example:

1
2
3
File.open("file.txt").each_line do |line|
  puts line
end


This code will open the file "file.txt" and read it one line at a time. Each line will be passed to the block as the "line" variable, and the code inside the block will be executed for each line. In this example, the code is simply printing each line to the console.