In this article, you will learn how to use the Ruby bytes method.
Using the bytes method
The bytes method in Ruby returns an array of bytes from a given string. It can be used to convert a string into an array of bytes, which can be useful in situations such as network communication or binary file handling.
Here’s how you can use the bytes method in Ruby:
The bytes method can be called on a string to return an array of bytes:
string = "hello" bytes = string.bytes puts bytes.inspect # => [104, 101, 108, 108, 111]
This will return an array of bytes representing the characters in the string.
If the string contains characters with non-ASCII encoding, you can specify the encoding to ensure correct conversion to bytes:
string = "こんにちは" bytes = string.bytes(Encoding::UTF_8) puts bytes.inspect # => [227, 129, 147, 227, 129, 130, 227, 129, 159, 227, 129, 152, 227, 129, 149]
Here, the Encoding::UTF_8 argument is passed to the bytes method to ensure that the string is correctly converted to bytes.
Byte offset and length
You can also specify the byte offset and length of the string to convert only a part of the string to bytes:
string = "hello" bytes = string.bytes(1, 3) puts bytes.inspect # => [101, 108, 108]
Here, the 1 argument specifies the byte offset (starting at index 1, which is the second character in the string), and the 3 argument specifies the length of the string to convert to bytes.
The bytes method can also be used with a block, which is called once for each byte in the string:
string = "hello" string.bytes do |byte| puts byte end
This will output each byte of the string on a new line.