从Ruby中的文件中读取每8个字节

时间:2014-08-19 02:44:54

标签: ruby filereader

我正在尝试读取ruby中的文件,但我需要每次读取8个字节 例:

file = "a1b2c3d4c5d6e7f8g9h0"
file.each_8_bytes do |f|
  puts f
end

输出

=> a1b2c3d4
=> c5d6e7f8
=> g9h0

我是怎么做到的?

2 个答案:

答案 0 :(得分:5)

f = File.open(file)
f.read(8) #=> a1b2c3d4
f.read(8) #=> c5d6e7f8
f.read(8) #=> g9h0
...
f.close

或者自动执行,

File.open(file) do |f|
  while s = f.read(8)
    puts s
  end
end

答案 1 :(得分:0)

如果要将结果放入数组中,则可能有足够的内存将整个文件读入字符串,在这种情况下,您可以执行以下操作。

text = "My dog has fleas.  Oh, my!"
File.write('temp', text) #=> 26

text = File.read('temp')
((text.size+7)/8).times.map { |i| text.slice(i*8,8) }
  #=> ["My dog h", "as fleas", ".  Oh, m", "y!"]

或者,如果您愿意:

((text.size+7)/8).times.map { text.slice!(0,8) }
相关问题