简体   繁体   中英

Ruby: character to ascii from a string

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
                ^

The c variable already contains the char code!

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

yields

115
116
114
105
110
103
puts "string".split('').map(&:ord).to_s

Ruby String provides the codepoints method after 1.9.1.

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

str = "你好世界"
str.codepoints.to_a
=> [20320, 22909, 19990, 30028]

请参考这篇文章,了解ruby1.9中的更改。 使用`(问号)在Ruby中获取ASCII字符代码失败

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]

对于单个字符,请使用“ x” .ord;对于整个字符串,请使用“ xyz” .sum。

"a"[0]

or

?a

Both would return their ASCII equivalent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM