此维基页面概述了如何将单个字符转换为ascii http:// en.wikibooks.org/wiki/Ruby_Programming/ASCII

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

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

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

这行不满意
syntax error, unexpected '?'
      $ascii = ?char
                ^
有帮助吗?

解决方案

c 变量已包含char代码!

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

产量

115
116
114
105
110
103

其他提示

puts "string".split('').map(&:ord).to_s

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

Ruby String在1.9.1之后提供 codepoints 方法。

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]

对单个字符使用“x”.ord或对整个字符串使用“xyz”.sum。

你也可以在each_byte之后调用to_a,甚至更好地调用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]
"a"[0]

?a

两者都会返回它们的ASCII等价物。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top