如何在Ruby中一次读取一个文件,一个字节? [英] how can I read a file, bytes at a time in Ruby?
本文介绍了如何在Ruby中一次读取一个文件,一个字节?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想迭代读取文件中固定数量的字节,然后将其返回
I want to iteratively read a fixed number of bytes in a file, and return them
我的代码如下.我是从互联网上的一个例子中摘录的
My code is below. I have taken it from an example on the internet
File.open('textfile.txt') do |file|
while (buffer = file.read(size)) do
yield buffer
end
end
我得到没有给出错误的错误.
I get the error no block given.
推荐答案
好吧,这是因为没有给出块.您可以将yield buffer
替换为puts buffer
(或任何所需的操作),或者创建一个带有代码块的单独方法:
Well, that's because no block is given. You can either replace yield buffer
with puts buffer
(or any operation you want) or create a separate method taking code block:
def read_file
File.open('textfile.txt') do |file|
while (buffer = file.read(size)) do
yield buffer
end
end
end
并这样称呼它
read_file do |data|
// do something with data
puts data
end
如有必要,将普通参数(如文件名或块大小)添加到read_file
.
Add normal parameters (like file name or block size) to read_file
, if necessary.
这篇关于如何在Ruby中一次读取一个文件,一个字节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文