14

例如:

"ASCII".is_ascii? # => true

"تجربة".is_ascii? # => false
4

2 回答 2

58

There is a bult-in Ruby string method right for you.

str.ascii_only? # → true or false

Returns true for a string which has only ASCII characters.

"abc".force_encoding("UTF-8").ascii_only?          #=> true
"abc\u{6666}".force_encoding("UTF-8").ascii_only?  #=> false
于 2010-09-27T11:47:21.250 回答
6

如果您的字符串是 Unicode(现在确实应该是),您可以简单地检查所有代码点是否为 127 或更少。Unicode 的底部 128 个代码点是 ASCII。

于 2010-09-26T12:01:11.633 回答