Ruby:将字符转换为字符串中的ASCII码

35

这个维基页面给出了将单个字符转换为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
                ^
7个回答

57

c变量已经包含了字符编码!

"string".each_byte do |c|
    puts c
end
产生的结果。
115
116
114
105
110
103

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

10
split('') 更好的方法是调用 chars - phoet

14

从1.9.1版本开始,Ruby字符串提供了codepoints方法。

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

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

3
你实际上需要在 codepoints 后添加 .to_a 吗?似乎 codepoints 已经返回一个数组 "abcde".codepoints.class #=> Array - dcts

12

使用"x".ord获取单个字符的ASCII码值,或者使用"xyz".sum获取整个字符串的ASCII码值总和。


8

在每个字节后面,您也可以直接调用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]

8

4
"a"[0]

或者

?a

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

4
Ruby 1.9 版本中有所改变吗? - Gishu
1
是的,在Ruby 1.8中它返回字符的ASCII值,但在Ruby 1.9中它返回索引处的字符... - David
10
"a"[0].ord 应该返回 ASCII 码。请注意,实际上它是 Unicode 码。 - albert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接