each_byte is a Ruby String method for traversing a string one byte at a time. With a block, it yields each byte as an integer and returns the original string; without a block, it returns an Enumerator. section 10.7 section 10.9.3
Inspecting bytes
str = "abcde" str.each_byte {|b| p b } # 97 # 98 # 99 # 100 # 101 The yielded values are byte codes, not one-character strings. For encoded text, byte iteration can produce more values than character or code-point iteration: "100€" yields 49, 48, 48, 226, 130, and 172 as bytes, but only four code points. section 10.7
Use each_byte in several related ways:
- Call it with a block to process bytes immediately: str.each_byte { |byte| ... }. section 10.9.3
- Call it without a block to obtain an enumerator, then chain operations such as map. section 10.9.3
- Choose each_char for characters, each_codepoint for character codes, or each_line for line-oriented traversal. section 10.7
- Use bytes when the operation is explicitly byte-oriented, especially when encoding makes characters occupy multiple bytes. section 10.7
Enumerator chaining in an XOR operation
class String def ^(key) kenum = key.each_byte.cycle each_byte.map { |byte| byte ^ kenum.next }.pack("C*") end end Here, key.each_byte creates byte iteration, cycle repeats the key indefinitely, and the receiver's each_byte supplies bytes for XOR. map collects the resulting integers, while pack("C*") rebuilds them into a string. Applying the same operation with the same key restores the original string. 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
Shows each_byte used both on the input string and on a cycling key enumerator. section 10.11.3
