tags:

views:

11240

answers:

5

Hi, this wiki page gave a general idea of how to convert a single char to ascii http://en.wikibooks.org/wiki/Ruby_Programming/ASCII

But say if I have a string and I wanted to get each character's ascii from it, what do i need to do?

"string".each_byte do |c|
      $char = c.chr
      $ascii = ?char
      puts $ascii
end

It doesn't work because it's not happy with the line $ascii = ?char

syntax error, unexpected '?'
      $ascii = ?char
                ^
+6  A: 

The c variable already contains the char code!

"string".each_byte do |c|
    puts c
end

yields

115
116
114
105
110
103
Konrad Rudolph
A: 

oh right! stupid me, thanks!

A: 

I came accross this when trying to figure out how to get a single ascii value. It was stupidly easy and I feel dumb for having to look it up but I'll post for others.

You just use the [] operator, ie:

irb(main):001:0> "string"[0] => 115

Sam
This is no longer true as of Ruby 1.9.
Chuck
No reason to vote down a once correct answer. Just comment that it's no longer true and the commenter can remove it. It's actually useful to see that the info no longer works too.
Mike Bethany
+2  A: 
"a"[0]

or

?a

Both would return their ASCII equivalent.

Mark F
Did this change in Ruby 1.9 ?
Gishu
Yea, in Ruby 1.8 it return the characters ascii value, but it ruby the character at the index in ruby 1.9...
David
+1  A: 

please refer to this post for the changes in ruby1.9 http://stackoverflow.com/questions/1270209/getting-an-ascii-character-code-in-ruby-fails

muddana