views:

57

answers:

1

I try to output the german setence containing the letter "ü" in escaped form (ascii 252, octal 374, hex 0xfc) using the following code:

pp "Test \374"
pp "Test \374".encode("UTF-8")

But using ruby 1.8.7 I get: "Test \374" "Test \374"

Using ruby 1.9.2 outputs: "Test \xFC" "Test \xFC"

How can I get ruby (1.8.7 + 1.9.x) to output "Test ü"? :)

+2  A: 
>> pp "Test \xc3\xbc"
"Test ü"
=> nil

>> s="Test \374"  # This has utf-8 encoding but we need it to be "ISO-8859-1"
=> "Test \xFC"
>> s.force_encoding("ISO-8859-1")
=> "Test "
>> s.encode("UTF-8")
=> "Test ü"
>> 
gnibbler
Why does my escape sequence not work? As I get the string from an external datasource, how can I convert it into your form so ruby can deal with it?
gucki
@gucki, your datasource is presumably ISO-8859-1 encoded. I added an example to show you how to change it. Better would be to open the datasource as ISO-8859-1 if possible
gnibbler
unluckily the datasource sometimes returns correct utf-8, sometimes iso-8859-1. but your solution works great, thanks :)
gucki