From: Ted Flethuseo on
Hi everyone,

I'm trying to write a couple of numbers to a binary file:

num = [1234567, 30, 40]
File.open("test.file", "wb") { |f|
num.each { |e| f.write e.to_i.pack("I") }
# f.write num.pack("I")
}

a = []
File.open("test.file", "rb") { |f|
a = f.read(4).unpack("I")
puts a
}

but I get errors for pack, I'd like to be able to use it such that I can
read
write several integers to binary file. I have seen it work for this code
(but it is only one int):

num = [1234567]
File.open("test.file", "wb") { |f|
num.each { |e| f.write e.to_i.pack("I") }
# f.write num.pack("I")
}

a = []
File.open("test.file", "rb") { |f|
a = f.read(4).unpack("I")
puts a
}

Any help appreciated.
Ted
--
Posted via http://www.ruby-forum.com/.

From: Joel VanderWerf on
Ted Flethuseo wrote:
> Hi everyone,
>
> I'm trying to write a couple of numbers to a binary file:
>
> num = [1234567, 30, 40]
> File.open("test.file", "wb") { |f|
> num.each { |e| f.write e.to_i.pack("I") }

you gotta put the integers in an array.

>> 3.pack "I"
NoMethodError: undefined method `pack' for 3:Fixnum
from (irb):1
>> [3].pack "I"
=> "\003\000\000\000"

And use * for your num array:

>> [1,2,3].pack "I*"
=> "\001\000\000\000\002\000\000\000\003\000\000\000"