如何将文件中的行读入数组

如何将文件中的行读入数组

本文介绍了如何将文件中的行读入数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 }

可能吗?

推荐答案

做如下:

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>

这篇关于如何将文件中的行读入数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:37