Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

String#unpack1

str.unpack1(format) → obj
str.unpack1(format, offset: anInteger) → obj

Decodes str (which may contain binary data) according to the format string, returning the first value extracted.

See also String#unpack, Array#pack.

Contrast with String#unpack:

Example
"abc \0\0abc \0\0".unpack('A6Z6')   #=> ["abc", "abc "]
"abc \0\0abc \0\0".unpack1('A6Z6')  #=> "abc"

In that case data would be lost but often it’s the case that the array only holds one value, especially when unpacking binary data. For instance:

Example
"\xff\x00\x00\x00".unpack("l")         #=>  [255]
"\xff\x00\x00\x00".unpack1("l")        #=>  255

Thus unpack1 is convenient, makes clear the intention and signals the expected return value to those reading the code.

The keyword offset can be given to start the decoding after skipping the specified amount of bytes:

Example
"abc".unpack1("C*") # => 97
"abc".unpack1("C*", offset: 2) # => 99
"abc".unpack1("C*", offset: 4) # => offset outside of string (ArgumentError)

Ruby version changes

  1. 3.1
See also #unpack #upcase #unicode_normalized? #upcase! also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2 · 3.0