Pod
Pod

Reputation: 968

Ruby decode string

In Ruby how can I get:

"b\x81rger" by providing the string "bürger".

I need to print special characters to a Zebra printer, I can see that "b\x81rger" prints "bürger", but sending "bürger" does not print the correct character.

Upvotes: 2

Views: 1038

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121020

Turns out it’s CP850.

Proper solution (Ruby 2.5+)

Normalize the unicode string and then encode it into CP850:

"bürger".unicode_normalize(:nfc).encode(Encoding::CP850)
#⇒ "b\x81rger"

Works for both special characters and combined diacritics.

Fallback solution (Ruby 2.5-)

Encode and pray it’s a composed umlaut:

"bürger".encode(Encoding::CP850)
#⇒ "b\x81rger"

Upvotes: 6

Related Questions