使用 `?`(问号)在 Ruby 中获取 ASCII 字符代码失败 [英] Getting an ASCII character code in Ruby using `?` (question mark) fails
问题描述
我需要一个字符的 ASCII 值(对于 Project Euler 问题 #22,如果你想具体一点),我遇到了一个问题.
I'm in a situation where I need the ASCII value of a character (for Project Euler question #22, if you want to get specific) and I'm running into an issue.
作为 ruby 的新手,我用 google 搜索,发现 ?
是要走的路:?A
或其他.但是当我将它合并到我的代码中时,该语句的结果是字符串 "A"
——没有字符代码.[0]
和 slice(0)
的问题相同,理论上两者都应该返回 ASCII 码.
Being new to ruby, I googled it, and found that ?
was the way to go: ?A
or whatever. But when I incorporate it into my code, the result of that statement is the string "A"
—no character code. Same issue with [0]
and slice(0)
, both of which should theoretically return the ASCII code.
我唯一能想到的是这是一个 ruby 版本的问题.我正在使用 1.9.1-p0,今天下午从 1.8.6 升级.我从 Ruby 的工作版本中作弊,在同一个目录中,我想我可能已经有了没有与 .zip 文件捆绑在一起的文件,所以我没有下载它们.
The only thing I can think of is that this is a ruby version issue. I'm using 1.9.1-p0, having upgraded from 1.8.6 this afternoon. I cheated a little going from a working version of Ruby, in the same directory, I figured I probably already had the files that don't come bundled with the .zip file, so I didn't download them.
那么为什么我所有的 ASCII 码都变成了实际的字符呢?
So why exactly are all my ASCII codes being turned into actual characters?
推荐答案
Ruby 1.9 之前的字符处理有些不一致.?a
和 "a"[0]
将返回一个整数,表示字符的 ASCII 值(这通常不是人们正在寻找的行为),但在实际使用字符通常由一个字符的字符串表示.在 Ruby 1.9 中,字符永远不会神秘地变成整数.如果要获取字符的 ASCII 值,可以使用 ord
方法,如 ?a.ord
(返回 97).
Ruby before 1.9 treated characters somewhat inconsistently. ?a
and "a"[0]
would return an integer representing the character's ASCII value (which was usually not the behavior people were looking for), but in practical use characters would normally be represented by a one-character string. In Ruby 1.9, characters are never mysteriously turned into integers. If you want to get a character's ASCII value, you can use the ord
method, like ?a.ord
(which returns 97).
这篇关于使用 `?`(问号)在 Ruby 中获取 ASCII 字符代码失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!