Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
communitycreator

What is the each_byte method in Ruby?

okwudili onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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}
Print each character in bytes in a string in Ruby

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.

RELATED TAGS

ruby
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring