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.
str.each_byte { |b| block }
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
.
The value returned is the bytes of each character that makes up a string.
# create some stringsstr1 = "Edpresso"# print each byte# reprentation of a characterstr1.each_byte {|b| puts b}
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.