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"


Strings

Numbers

Date and Time

Arrays

Hashes

Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming

XML and HTML

Graphics and Other File Formats

Databases and Persistence

Internet Services

Web Development Ruby on Rails

Web Services and Distributed Programming

Testing, Debugging, Optimizing, and Documenting

Packaging and Distributing Software

Automating Tasks with Rake

Multitasking and Multithreading

User Interface

Extending Ruby with Other Languages

System Administration



Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399

Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net