Ruby Binary Strings vs Byte Arrays

In Ruby, binary strings ("String") and byte arrays ("Array" of integers) both represent sequences of bytes, but they have key differences in mutability, indexing, and usage.


Key Differences Between a Binary String and a Byte Array

Feature Binary String ("String") Byte Array ("Array" of Integers)
Type "String" (holds raw binary data) "Array" (holds integers, 0-255)
Mutability Mutable Mutable
Storage Contiguous sequence of bytes Collection of separate integers
Indexing Returns a string ("\xNN") Returns an integer ("0-255")
Modification Modifies in-place using "[]=" Can modify individual elements
Performance More memory-efficient Slightly slower due to array overhead
Use Cases File I/O, networking, cryptography Byte-wise manipulation, calculations

Binary String

A binary string in Ruby is a "String" object that contains raw bytes.

Creating a Binary String

binary_string = "\x00\x01\x02\x03\x04"
puts binary_string.bytes.inspect  # Output: [0, 1, 2, 3, 4]

Accessing Bytes in a Binary String

puts binary_string[0]  # Output: "\x00" (a 1-byte string, not an integer)
puts binary_string.getbyte(0)  # Output: 0 (integer representation)

# Another way:
binary_string.each_byte { |byte| puts byte }

Modifying a Binary String

binary_string.setbyte(0, 255)  # Modifies the first byte to 255
puts binary_string.bytes.inspect  # Output: [255, 1, 2, 3, 4]

Binary-safe: Ruby "String" objects do not assume encoding unless explicitly set.


Byte Array

A byte array in Ruby is an "Array" of integers, where each element represents a byte ("0-255").

Creating a Byte Array

byte_array = [0, 1, 2, 3, 4]
puts byte_array.inspect  # Output: [0, 1, 2, 3, 4]

Accessing and Modifying a Byte Array

puts byte_array[0]  # Output: 0 (integer)
byte_array[0] = 255  # Modifies the first byte
puts byte_array.inspect  # Output: [255, 1, 2, 3, 4]