What is the each_byte method in Ruby?

Overview

The each_byte method in Ruby is used to pass the byte representation of each character in a string to a block.

A block is a loop in Ruby. It takes a single parameter. In this case, it takes the byte representation of each character that makes up a string.

String

str.each_byte { |b| block }

Parameters

  • str: This is the string that contains the characters whose bytes we want to pass to the block.

  • b: This is the parameter we pass to the block of our each_byte method. It represents the byte representation of each character of the string str.

Return value

The value returned is the bytes of each character that makes up a string.

Code

# create some strings
str1 = "Edpresso"
# print each byte
# reprentation of a character
str1.each_byte {|b| puts b}

Explanation

In the code given above, we were able to print the byte of each character of the string str1.

As is shown in output, the character "E" has a byte representation of 69, the character "d" has a byte representation of 100, and so on. Additionally, "s" has a string representation of 115, which we print twice in the code above.

Free Resources