A byte is a unit of digital data represented by an integer. Strings consist of sequences of bytes, but the mapping from bytes to characters depends on encoding; one character may occupy one or more bytes. section 10.11.3 section 8.1.6
Bytes become visible when Ruby processes strings and input streams at a low level:
- Use each_byte to enumerate a string's byte values rather than its characters. section 10.11.3
- Use getbyte to move through a file or IO stream byte by byte; getc instead returns characters. section 12.2.3
- Remember that byte counts and character counts can differ when the encoding uses multiple bytes per character. section 12.2.3
- Treat IO#write's return value as the number of bytes written. section 12.1.1
XOR-ing string bytes
The string "a" contains one byte with value 97. XOR-ing it with 35, the value associated with "#", produces 66: 97 ^ 35. Applying the same XOR again restores 97, because (a ^ b) ^ b == a. Repeating a key across a string therefore provides a reversible byte-wise transformation. section 10.11.3
Listing 10.6 An exclusive-or method for strings
class String
def ^(key) 1
kenum = key.each_byte.cycle 2
each_byte.map {|byte| byte ^ kenum.next }.pack("C*") 3
end
end
This compact method cycles through a key's bytes, XORs them with the receiver's bytes, and packs the resulting integers back into a string. section 10.11.3






