Converting Between Characters and Values
Problem
You want to see the ASCII code for a character, or transform an ASCII code into a string.
Solution
To see the ASCII code for a specific character as an integer, use the ? operator:
?a # => 97 ?! # => 33 ? # => 10
To see the integer value of a particular in a string, access it as though it were an element of an array:
'a'[0] # => 97 'bad sound'[1] # => 97
To see the ASCII character corresponding to a given number, call its #chr method. This returns a string containing only one character:
97.chr # => "a" 33.chr # => "!" 10.chr # => " " 0.chr # => "00" 256.chr # RangeError: 256 out of char range
Discussion
Though not technically an array, a string acts a lot like like an array of Fixnum objects: one Fixnum for each byte in the string. Accessing a single element of the "array" yields a Fixnum for the corresponding byte: for textual strings, this is an ASCII code. Calling String#each_byte lets you iterate over the Fixnum objects that make up a string.
See Also
- Recipe 1.8, "Processing a String One Character at a Time"