ruby 如何从文件中读取行到数组中?

gkl3eglg  于 2023-04-05  发布在  Ruby
关注(0)|答案(1)|浏览(127)

这就是我想做的,但只有一行代码:

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

可能吗?

ih99xse1

ih99xse11#

请执行以下操作:

File.readlines('test.txt')

阅读文档:

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.

示例

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>

相关问题