views:

38

answers:

3

For example something like:

"ASCII".is_ascii? # => true

"تجربة".is_ascii? # => false
+1  A: 

The excellent blog article at http://blog.grayproductions.net/articles/ruby_19s_string explains the issue quite well I think.

abc = "Hello, world"
puts abc.encoding.name  # US-ASCII

The same article also explains converting between the two.

jelford
+1  A: 

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.

paxdiablo
A: 

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
Semyon Perepelitsa