String#unpack1
str.unpack1(format) -> object Object · Updated March 13, 2026 · String Methods The unpack1 method is part of Ruby’s pack/unpack functionality, which converts binary data between its raw byte representation and Ruby objects. Unlike unpack which returns an array of all decoded values, unpack1 returns only the first element.
Understanding Pack and Unpack
Ruby’s pack and unpack methods provide a way to convert between binary data (stored as strings) and Ruby objects. This is essential when working with network protocols, file formats, binary files, or any situation where you need to interpret raw byte data.
The format string tells Ruby how to interpret the bytes. Each character in the format string corresponds to a different data type, similar to how C’s struct module works.
Practical Examples
Basic Usage
# Unpack a single integer from 4 bytes
binary = [42].pack("l") # Little-endian signed long
binary.unpack1("l") # => 42
# Extract first value from multiple packed values
data = [255, 128, 64].pack("C*") # Three unsigned bytes
data.unpack1("C") # => 255 (only the first byte)
Working with Network Data
# IP addresses are 4 bytes
ip_bytes = [192, 168, 1, 1].pack("C*")
ip_bytes.unpack1("C") # => 192
# Port numbers are 2 bytes
port_bytes = [8080].pack("n") # Network byte order (big-endian)
port_bytes.unpack1("n") # => 8080
Extracting Structured Data
# Header contains: version (1 byte), length (2 bytes), type (1 byte)
header = [1, 256, 65].pack("C*")
header.unpack1("C") # => 1 (version)
header.unpack("C n") # => [1, 256] (both values)
header.unpack1("n") # => 256 (length only, skips version)
Binary File Parsing
# Reading a BMP file header
File.open("image.bmp", "rb") do |f|
header = f.read(14)
file_size = header.unpack1("l") # 4 bytes, little-endian
reserved = header[4..5].unpack1("s") # 2 bytes
offset = header[10..13].unpack1("l") # pixel data offset
puts "File size: #{file_size}, Offset: #{offset}"
end
Common Format Directives
C- Unsigned bytec- Signed byteS- Unsigned 16-bit little-endians- Signed 16-bit little-endiann- Unsigned 16-bit big-endian (network order)l- Signed 32-bit little-endianL- Unsigned 32-bit little-endianf- Floatd- DoubleA- ASCII string (trailing nulls and spaces removed)
Why Use unpack1?
The main advantage of unpack1 is clarity and efficiency when you only need one value. It avoids creating an array when you only want a single result, making your code more expressive and slightly more efficient.
# More readable than unpack[0]
result = data.unpack1("N")
# vs
result = data.unpack("N")[0]
This method is particularly useful in performance-critical code where you’re processing large amounts of binary data.