What is the getbyte() method in Ruby?

Overview

In Ruby, the getbyte() method is used to return a byte or ASCIIAmerican Standard Code for Information Interchange value of a character in a string.

Syntax

 int getbyte( int index)

Parameters

This method takes the parameter index. It represents the index position of the character whose byte value we want to get.

Return value

It returns an integer value that is the byte representation of a character.

Code

# create a string
str = "Edpresso";
# get byte of some characters and printing them
puts str.getbyte(0) # first character
puts str.getbyte(3) # fourth character
puts str.getbyte(7) # last character

Explanation

  • Line 2: We create and initialize a string variable str.
  • Lines 5–7: We call the getbyte() method on the string str to get the bytes of several characters. We print these using puts. Next, we pass the index position value of the characters to getbyte(). It returns the bytes of the characters.

When the code above is run, the byte value of the characters is printed to the console.

Free Resources