35

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
                ^
user2668
  • 353
  • 1
  • 3
  • 4

7 Answers7

57

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
  • 530,221
  • 131
  • 937
  • 1,214
22
puts "string".split('').map(&:ord).to_s
Rafał Rawicki
  • 22,324
  • 5
  • 59
  • 79
alexsuslin
  • 4,130
  • 1
  • 20
  • 30
12

use "x".ord for a single character or "xyz".sum for a whole string.

Sh.K
  • 289
  • 3
  • 4
12

Ruby String provides the codepoints method after 1.9.1.

str = 'hello world'
str.codepoints
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] 

str = "你好世界"
str.codepoints
=> [20320, 22909, 19990, 30028]
Community
  • 1
  • 1
LastZactionHero
  • 269
  • 2
  • 10
  • 3
    do you actually need the `.to_a` after codepoints? Seems like `codepoints` already returns an array `"abcde".codepoints.class #=> Array` – dcts Apr 13 '19 at 22:27
8

please refer to this post for the changes in ruby1.9 Getting an ASCII character code in Ruby using `?` (question mark) fails

Community
  • 1
  • 1
8

You could also just call to_a after each_byte or even better String#bytes

=> 'hello world'.each_byte.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

=> 'hello world'.bytes
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]
nikkypx
  • 1,925
  • 17
  • 12
4
"a"[0]

or

?a

Both would return their ASCII equivalent.

Mark
  • 39,169
  • 11
  • 42
  • 48