PDA

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


Derleth
12-25-2002, 03:10 PM
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.

friedo
12-25-2002, 03:50 PM
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, ' ' }


Produces

104 101 108 108 111

Derleth
12-25-2002, 04:00 PM
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! :)