繁体   English   中英

Ruby:字符从字符串转换为ASCII

[英]Ruby: character to ascii from a string

该Wiki页面给出了有关如何将单个字符转换为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

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]

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

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

对于单个字符,请使用“ x” .ord;对于整个字符串,请使用“ xyz” .sum。

"a"[0]

要么

?a

两者都将返回等效的ASCII码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM