From: Sam Duncan Date: 2013-04-18T05:37:14+09:00 Subject: Re: String index produces unanticipated result On 04/18/2013 08:24 AM, Thomas Luedeke wrote: > I have the following string I am pulling from a file (asterisks used to > show boundaries of line, and are not actually there: > > * 9 3 3 0 0* > > I want to test to see if a "9" is in the first five columns of the line. > Typically it is in column five, but not necessarily. > > I tried the "puts line.strip[0]" command, which returns "57". Huh? > Where did "57" come from?? Same thing happens with strip!. > > Why isn't this simply removing the leading white space and returning > "9"?? I don't understand how to accomplish my task now. > > I tried the online irb, and it gave me "9", like I'd have expected. > The 57 you are getting is the ordinal of the string "9"; irb(main):001:0> "9".ord => 57 In Ruby 1.8 I believe an index into a string gave you this value, rather than the character at that index. In Ruby 1.9 it was changed to give you what you are expecting here; irb(main):002:0> "9"[0] => "9" Something like this would probably work for you in both flavours of Ruby; irb(main):003:0> foo.split[0,5].include? "9" => true Split the string, take a slice of the first five values (columns), and check for membership. Sam