如何读取文件到数组的行?

yeg*_*256 18 ruby

这就是我想要做的,但如果可能的话,使用单线程:

lines = Array.new
File.open('test.txt').each { |line| lines << line }
Run Code Online (Sandbox Code Playgroud)

可能?

Aru*_*hit 46

请执行以下操作:

File.readlines('test.txt')
Run Code Online (Sandbox Code Playgroud)

阅读文档:

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.
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

  • 我的意思是,这只是如此出色且设计精良的语言的又一个例子。你想从“文件”中“读取行”到数组中,Ruby 的答案是“File.readlines(filename)”。:) (2认同)