Read every 8 bytes from a file in Ruby
I am trying to read a file in ruby, but I need to read 8 bytes at a time. Example :.
file = "a1b2c3d4c5d6e7f8g9h0"
file.each_8_bytes do |f|
puts f
end
Output
=> a1b2c3d4
=> c5d6e7f8
=> g9h0
how do i do it?
+3
gFontaniva
source
to share
2 answers
f = File.open(file)
f.read(8) #=> a1b2c3d4
f.read(8) #=> c5d6e7f8
f.read(8) #=> g9h0
...
f.close
Or do it automatically,
File.open(file) do |f|
while s = f.read(8)
puts s
end
end
+5
sawa
source
to share
If you are putting the results into an array, you probably have enough memory to read the entire file into a string, in which case you can do the following.
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!"]
or, if you like:
((text.size+7)/8).times.map { text.slice!(0,8) }
0
Cary swoveland
source
to share