Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read lines from file into array?

Tags:

ruby

This is what I want to do, but with a one-liner, if possible:

lines = Array.new File.open('test.txt').each { |line| lines << line } 

Possible?

like image 426
yegor256 Avatar asked Aug 06 '14 19:08

yegor256


People also ask

How do you read a line in a file C?

The standard way of reading a line of text in C is to use the fgets function, which is fine if you know in advance how long a line of text could be.

How do you read an array line in Python?

Python read file line by line into arrayAn empty array is defined and the argument is opened as f and to read the line. The for line in f is used and to append the line into the array, array. append is used. The fruits file is passed as the parameter in the function.

How do I read a text file line by line in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.


1 Answers

Do as below :

File.readlines('test.txt') 

Read documentation :

arup@linux-wzza:~> ri IO::readlines  = IO::readlines  (from ruby site) ------------------------------------------------------------------------------   IO.readlines(name, sep=$/ [, open_args])     -> array   IO.readlines(name, limit [, open_args])      -> array   IO.readlines(name, sep, limit [, open_args]) -> array  ------------------------------------------------------------------------------  Reads the entire file specified by name as individual lines, and returns those lines in an array. Lines are separated by sep.    a = IO.readlines("testfile")   a[0]   #=> "This is line one\n"  If the last argument is a hash, it's the keyword argument to open. See IO.read for detail. 

Example

arup@linux-wzza:~/Ruby> cat out.txt name,age,location Ram,12, UK Jadu,11, USA arup@linux-wzza:~/Ruby> ruby -e "p File::readlines('./out.txt')" ["name,age,location\n", "Ram,12, UK\n", "Jadu,11, USA\n"] arup@linux-wzza:~/Ruby> 
like image 95
Arup Rakshit Avatar answered Sep 20 '22 18:09

Arup Rakshit