将整个文本文件作为单个字符串读取的合理方法是什么? [英] What's a reasonable way to read an entire text file as a single string?

查看:111
本文介绍了将整个文本文件作为单个字符串读取的合理方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确信这很容易;我无法立即从Google找到答案

I am sure this is an easy one; I just couldn't find the answer immediately from Google.

我知道我可以做到这一点(对吧?):

I know I could do this (right?):

text = ""
File.open(path).each_line do |line|
    text += line
end

# Do something with text

但这似乎有点过分,不是吗?或者这是用Ruby做的方式?

But that seems a bit excessive, doesn't it? Or is that the way one would do it in Ruby?

推荐答案

IO.read()

编辑: IO.read(),作为额外的奖励,为您关闭文件。

IO.read(), as an added bonus, closes the file for you.

这篇关于将整个文本文件作为单个字符串读取的合理方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆