开发者

How to check a String if it's an ASCII or not?

For example something like:

"ASCII".is_asci开发者_StackOverflowi? # => true

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


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


If your strings are Unicode (and they really should be, nowadays), you can simply check that all code points are 127 or less. The bottom 128 code points of Unicode are ASCII.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜