yegor256
yegor256

Reputation: 105210

How to read lines from file into array?

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

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

Possible?

Upvotes: 36

Views: 42260

Answers (2)

spier
spier

Reputation: 2752

I use the same File.readlines methods as explained in the accepted answer.

However when I read in strings from a text file, I typically want to get rid of the newline characters at the end of each line.

Therefore I use this:

 File.readlines('adopters.txt').map(&:chomp)

Upvotes: 2

Arup Rakshit
Arup Rakshit

Reputation: 118299

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>

Upvotes: 77

Related Questions