From: Robert Klemme Date: 2010-01-18T04:30:11+09:00 Subject: Re: Strange Encoding Behavior On 01/17/2010 04:55 AM, Lui Kore wrote: > The encoding of __FILE__ is always the same as Encoding.default_external > even if there is a magic column. Sometimes it is necessary to convert > the string into another encoding. Here is some code to demonstrate the > issue: > > #coding: utf-8 > # put the script in a not-pure-ascii path to see the difference > path = File.expand_path File.dirname __FILE__ > > puts RUBY_VERSION + ' ' + RUBY_PLATFORM > #=> "1.9.1 i386-mingw32" is my ruby version > puts path.encoding > #=> "GB2312" on my OS > > # usually this "string.encode to, from" works, > # but HERE the new string's content bytes seems unchanged > puts \ > path.encode 'utf-8', Encoding.default_external > > path.force_encoding Encoding.default_external > puts path.encode 'utf-8' > # changed at last I believe the point you are missing is that String#encode does not change the String but it returns a new String with the desired encoding. If you want inplace modification you need to use String#encode! which does just that. irb(main):006:0> s="foo" => "foo" irb(main):007:0> s.encoding => # irb(main):008:0> x = s.encode "ASCII" => "foo" irb(main):009:0> s.encoding => # irb(main):010:0> x.encoding => # irb(main):011:0> Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/