From: Marcel Ward Date: 2006-11-03T00:05:56+09:00 Subject: Re: String#unpack On 02/11/06, Joe Van Dyk wrote: > Hi, > > I have a string that contains only a C int. Is the way to get it out: > > the_string.unpack("i").first > Looks ok to me. You should of course double check that both your string data and Ruby's parsing share the same size and endian-ness on all the platforms you will be working with. Also check out the 'i_' option if you want to unpack according to the system's native byte order. > ? Is there another method that doesn't return an array? I'm not sure. At least it should be one of the fastest ways because it's coded in C - see pack.c. The String#unpack method can extract multiple elements from a string so it always returns an array cotaining the elements. For example, a string containing 16 bytes of data representing 4 int values can be extracted with: "A\0\0\0B\0\0\0C\0\0\0D\0\0\0".unpack("iiii") # => [65, 66, 67, 68] So there is a good reason for it to be returning an array. You can always write a wrapper for the single int operation if you want your code to look cleaner. class String def unpack_first_int unpack("i").first end end "A\0\0\0B\0\0\0C\0\0\0D\0\0\0".unpack_first_int # => 65 -- Marcel