Ruby Ruby char ASCII 相互转换

saxer · May 14, 2015 · Last by saxer replied at May 26, 2015 · 5771 hits

ASCII => char

97.chr       #=> "a"

char => ASCII

'a'.ord       #=> 97
'\t'.ord      #=> 92

字符串可以试试 pack/unpack

[104, 101, 108, 108, 111].pack 'c*'
'hello'.unpack 'c*'

有个简单通用的方法:

"中文abc".codepoints
=> [20013, 25991, 97, 98, 99]

倒过来:

 "中文abc".codepoints.map{|x| x.chr('UTF-8') }.join
=> "中文abc"

#2 楼 @gihnius 这个好!!

You need to Sign in before reply, if you don't have an account, please Sign up first.