How to read whole file in Ruby?

ε祈祈猫儿з 提交于 2019-12-18 03:00:26

问题


Is there an in-built function in Ruby to read the whole file without using any loop? So far, I have only come across methods that read in chunks (line or character).


回答1:


IO.read("filename")

or

File.read("filename")



回答2:


File.readlines("filename")

This is also a great method to read everything from a file and break split on carriage returns. The return is an Array with one line per element.




回答3:


Please ignore advice which states "You should never slurp (which is the annoying term for this) a file". Sometimes this is a very useful, and sensible thing to do.

Suppose you're reading a file repeatedly : good chance that reading the file into an array is a sensible optimisation over reading the file line by line, even taking into account that the o/s will cache the file.



来源:https://stackoverflow.com/questions/3328495/how-to-read-whole-file-in-ruby

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!