Byte arrays

Jeff Massung wrote:

Sorry for [what is probably] a very newbie question, but is there any way
to specify just a straight byte array in Ruby? I want to just be able to
write the array directly to a binary file, but using regular ints will (I’m
assuming) write 32-bit values, and not bytes.

I’m sure there is a very simple way to do what I want (probably just using
the IO class), but I haven’t seen a writebytes or similar function yet. I’d
even consider using strings if needed.

Thanks.


Best regards,
Jeff Massung jma[at]mfire.com
http://www.jm-basic.com/

IO#putc writes Fixnums etc. as 8-bit values.

···

#--------------------------------------
File.open(‘wbtest.txt’, ‘wb’) do |wbf|
ba = [‘A’, 66, ‘Chop’, ?D, “\n”]
ba.each {|b| wbf.putc b}
wbf.write(“END\n”)
end

File.open(‘wbtest.txt’, ‘rb’) { |wbf| p wbf.read } # Check what’s there

#=> “ABCD\nEND\n”
#--------------------------------------

Add new IO method ??

class IO

def writebytes(arr)

arr.each {|b| putc b}

end

end

wbf.writebytes(ba)

daz