sbs sbs - 4 months ago 6x
Ruby Question

How to check if a string contains ASCII code

Given a string

, it can be converted to utf-8 string by doing this (ref link):

"A\xC3B".force_encoding('iso-8859-1').encode('utf-8') #=> "AÃB"

However, I only want to perform the action if the string contains the ASCII code, namely
. How can I check for that?

but it doesn't work.


\x is just a hexadecimal escape sequence. It has nothing to do with encodings on its own. US-ASCII goes from "\x00" to "\x7F" (e.g. "\x41" is the same as "A", "\x30" is "0"). The rest ("\x80" to "\xFF") however are not US-ASCII characters since it's a 7-bit character set.

If you want to check if a string contains only US-ASCII characters, call String#ascii_only?:

p "A\xC3B".ascii_only? # => false
p "\x41BC".ascii_only? # => true

Another example based on your code:

str = "A\xC3B"
unless str.ascii_only?
p str.encoding # => #<Encoding:UTF-8>