Ruby programming language: Treating a text stream as an array of bytes.

How can I get a Ruby program to treat an array of characters (or a character string, undifferentiated) as an array of C-style character literals? I desire the ability to input an ASCII string and then perform arithmetic on the byte values of individual characters. What is a good way to do this?

Note: I am not trying to convert an ASCII representation of a hexadecimal number into a numerical value. (Through “f”.hex == 15, for example.) I am trying to accomplish what in C I would accomplish by casting a character value to int.

The problem with this is that Ruby doesn’t have any literals, but you can treat String objects as arrays of integers:

a = "hello"

a[0]  ---> returns integer 104.

You can also pass a block to the each_byte method to loop over the bytes in the string:

"hello".each_byte {|c| print c, ' ' }


104 101 108 108 111

Thank you. The each_byte iterator is precisely what I need.

The ability to treat string objects as arrays of integers is also very helpful.

Heh heh. My Ruby CipherSaber-2 implementation is nearly complete! :slight_smile: