From: RichardOnRails Date: 2008-09-13T15:38:46+09:00 Subject: Re: Beginner User having issue with converting char to ASCII On Sep 12, 8:20 pm, Todd Benson wrote: > On Fri, Sep 12, 2008 at 6:40 PM, James Gray wrote: > > On Sep 12, 2008, at 5:25 PM, Nick Bo wrote: > > >> my issue is I dont know how to take the character > >> and convert it into ASCII. > > > In Ruby 1.8 you can just index into the String and Ruby will return the > > character value: > > >>> "a"[0] > > => 97 > > > Hope that helps and welcome to Ruby! > > Also, if you are required to iterate, you can do String#each_byte > after an Array#join, but I don't think that's what you are looking > for, but I couldn't resist (I know I'm a clown)... > > [('a'..'z'),('A'..'Z'),('0'..'9')].inject([]){|s,i|s+i.map}.join.each_byte{|b|p > b} > > If you need to do an each/do, you should probably do as James suggests. > > Todd Hi Nick, James and Todd gave you good ideas. But because you're a newbie, you may need a solution that exactly meets your stated requirements. Your explicit coding of a string of the required character using a blank separator is fine (except for the embedded ellipses [...]). The "Ruby Way" is to generate such things. http://www.pastie.org/271697 offers two solutions: A succinct version (12 lines separated by three blank lines) and an instrument version (23 lines). The succinct version shows: Section 1 (Line 1): Define “array” containing a reference to an Array object, which in turn contains references to three Range objects that contain respectively single-letter strings: lower-case letters, upper-case letters and decimal-digit characters. Section 2 (Lines 3-8) defines an initially empty string named “characters”. We successively process each range, In processing a range, we process each one-character string contained therein appended the string’s content to “characters:”. Section 3 (Line 10) splits the “characters” string using the nil string (‘’), which creates an array of all the one-character strings and puts a reference to it in split_chs. Section 4 (Lines 12-14) processes each one-character string in the array referenced by “split_chs”. The character and its numeric code representing it is displayed as a line of output. Altogether, 62 lines are generated. Line 15 provides an alternative to the coding of line 13 if Ruby 1.9 or greater is being used. The instrument version displays the intermediate values as they’re computed. That may be helpful in understanding the code. HTH, Richard