从本地文件或 url 打开 IO 流 [英] Open an IO stream from a local file or url
本文介绍了从本地文件或 url 打开 IO 流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道有其他语言的库可以采用包含本地文件路径或 url 的字符串,并将其作为可读 IO 流打开.
I know there are libs in other languages that can take a string that contains either a path to a local file or a url and open it as a readable IO stream.
在 ruby 中是否有一种简单的方法可以做到这一点?
Is there an easy way to do this in ruby?
推荐答案
open-uri 是标准 Ruby 库的一部分,它将重新定义 open
的行为,以便您可以打开 url 以及本地文件.它返回一个 File
对象,因此您应该能够调用诸如 read
和 readlines
之类的方法.
open-uri is part of the standard Ruby library, and it will redefine the behavior of open
so that you can open a url, as well as a local file. It returns a File
object, so you should be able to call methods like read
and readlines
.
require 'open-uri'
file_contents = open('local-file.txt') { |f| f.read }
web_contents = open('http://www.stackoverflow.com') {|f| f.read }
这篇关于从本地文件或 url 打开 IO 流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文