Search code examples
rubyruby-on-rails-3utf-8iconv

How can I convert a String with \xf6 chars into a human readable one?


Currently I'm working on an Rails application with PayPal checkout. PayPal communicates with my app with IPN messages.

In many cases everything works fine, but if someone uses special chars like German umlauts (öüäß) I get \xf6 in the string.

How can I convert this into the human readable char 'ö'?


Solution

  • The problem is that the data was encoded as Windows-1252, but ruby won't detect that automatically. You can coax it like this:

    my_string = "Sch\xF6ning"
    my_string.force_encoding('windows-1252').encode('utf-8')
    => "Schöning"
    

    You can make a reusable converter to help you do the same thing:

    ec = Encoding::Converter('windows-1252', 'utf-8')
    ec.convert(my_string)
    => "Schöning"