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 

它不起作用,因为它对行$ 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字符代码失败

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

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] 
 "a"[0] 

要么

 ?a 

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

您也可以在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]