ruby 如何将文件中的行读入数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25168662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:33:02 来源:igfitidea点击:
How to read lines from file into array?
提问by yegor256
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 }
Possible?
可能的?
回答by Arup Rakshit
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>

![ruby ActionController::RoutingError(没有路由匹配 [GET]](/res/img/loading.gif)