# In 1.9.2, with force\_encoding, we still need iconv?

**URL:** <https://www.ruby-forum.com/t/in-1-9-2-with-force-encoding-we-still-need-iconv/202539>\
**Category:** Rails I18n\
**Created:** [February 1, 2011, 3:55am UTC](https://www.ruby-forum.com/t/in-1-9-2-with-force-encoding-we-still-need-iconv/202539 "2011-02-01T03:55:28Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dubstep](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/cdc98d/32.png) [@dubstep](https://www.ruby-forum.com/u/dubstep)\
**Post date:** [February 1, 2011, 3:55am UTC](https://www.ruby-forum.com/t/in-1-9-2-with-force-encoding-we-still-need-iconv/202539/1 "2011-02-01T03:55:28Z")

</div>

I got code in ruby 1.8.  
Iconv.iconv(‘gbk’, ‘utf-8’, string)

now, ruby 1.9.2 has force\_encoding(‘utf-8’), so can I just  
forceing\_encoding(‘utf-8’) ?

---

<div class="post-metadata">

**Author:** ![rubyernewbie](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/9dc877/32.png) [@rubyernewbie](https://www.ruby-forum.com/u/rubyernewbie)\
**Post date:** [February 1, 2011, 4:41am UTC](https://www.ruby-forum.com/t/in-1-9-2-with-force-encoding-we-still-need-iconv/202539/2 "2011-02-01T04:41:29Z")

</div>

On 2011/02/01 11:55, Zhenning G. wrote:

> I got code in ruby 1.8.  
> Iconv.iconv(‘gbk’, ‘utf-8’, string)
> 
> now, ruby 1.9.2 has force\_encoding(‘utf-8’), so can I just  
> forceing\_encoding(‘utf-8’) ?

No. force\_encoding just changes the encoding label, but leaves the bytes  
in the string as they are. That would result in garbage (unless  
everything is ASCII anyway). The main use of force\_encoding is to set  
encoding labels for raw byte strings (e.g. coming from outside) when  
knowing already what the encoding is.

The equivalent of your Iconv call, in Ruby 1.9, is:

string.encode(‘gbk’, ‘utf-8’)

But I’m a bit vary about the order of the arguments. Both  
Iconv.iconv(‘gbk’, ‘utf-8’, string)  
string.encode(‘gbk’, ‘utf-8’)

encode from UTF-8 to GBK, but the result of force\_encoding(‘utf-8’) is  
UTF-8, so if you want the result to be UTF-8, you have to turn the order  
of the parameters around. I was never happy with the TO-FROM order in  
iconv, and I’m also not happy with the TO-FROM order in String#encode,  
but String#encode can also be used just with the TO parameter, e.g. just  
string.encode(‘gbk’)  
if the string has the correct encoding at this point. So when we (Matz  
and me, mainly) designed String#encode, unfortunately TO-FROM was the  
only order that made sense.

Please also note that there might be slight differences between Iconv  
and String#encode for some characters, but these should be very small in  
number.

Regards, Martin.

–  
#-# Martin J. Drst, Professor, Aoyama Gakuin University  
#-# [http://www.sw.it.aoyama.ac.jp](http://www.sw.it.aoyama.ac.jp)[mailto:removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
