Ruby:来自字符串的ascii字符

use*_*668 28 ruby ascii

这个维基页面提供了如何将单个字符串转换为ascii的一般概念http://en.wikibooks.org/wiki/Ruby_Programming/ASCII

但是说如果我有一个字符串并且我想从中获取每个字符的ascii,我需要做什么?

"string".each_byte do |c|
      $char = c.chr
      $ascii = ?char
      puts $ascii
end
Run Code Online (Sandbox Code Playgroud)

它不起作用,因为它对行$ ascii =?char不满意

syntax error, unexpected '?'
      $ascii = ?char
                ^
Run Code Online (Sandbox Code Playgroud)

Kon*_*lph 53

c变量已包含char代码!

"string".each_byte do |c|
    puts c
end
Run Code Online (Sandbox Code Playgroud)

产量

115
116
114
105
110
103
Run Code Online (Sandbox Code Playgroud)


ale*_*lin 19

puts "string".split('').map(&:ord).to_s
Run Code Online (Sandbox Code Playgroud)

  • 甚至比`split('')更好叫`chars` (10认同)

Las*_*ero 9

Ruby String提供codepoints1.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]
Run Code Online (Sandbox Code Playgroud)

  • 在代码点之后你真的需要`.to_a`吗?似乎 `codepoints` 已经返回一个数组 `"abcde".codepoints.class #=> Array` (2认同)

小智 8

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


nik*_*ypx 7

您也可以在each_byte甚至更好的String#bytes之后调用to_a

=> '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]
Run Code Online (Sandbox Code Playgroud)


小智 6

对单个字符使用"x".ord或对整个字符串使用"xyz".sum.