liveBook · Manning

Each_byte

As explained in The Well-Grounded Rubyist, Fourth Edition

each_byte is a Ruby String method that iterates over a string's bytes and can return an enumerator when no block is supplied.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains block iteration, return behavior, implicit enumerators, chaining, and encoding differences without exhaustively specifying internals.
Examples
Uses ASCII byte printing, multibyte Euro-sign output, blockless enumeration, and reversible XOR string transformation.
What it assumes
Assumes basic Ruby strings and blocks while demonstrating enumerators through blockless iterator calls.
What you can do after
Apply it via Ruby blocks and enumerator chains to inspect or transform string bytes.
How it connects
Connects String with Enumerator, map, cycle, pack, each_char, each_codepoint, each_line, and encoding.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.