gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:32:49 27 4
gpt4 key购买 nike

这就是我想做的,但如果可能的话,使用单行代码:

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

可能吗?

最佳答案

做如下:

File.readlines('test.txt')

阅读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.

示例

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>

关于ruby - 如何从文件中读取行到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168662/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com