这个维基页面提供了如何将单个字符串转换为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)
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)
您也可以在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)
| 归档时间: |
|
| 查看次数: |
95937 次 |
| 最近记录: |