change string encoding in ruby

Posted . Visible to the public.
# Ruby 1.9
string_in_utf8_encoding = string_in_latin1_encoding.encode('UTF-8')

#Ruby 1.8
gem install iconv

require 'iconv'
string_in_utf8_encoding = Iconv.conv("UTF8", "LATIN1", string_in_latin1_encoding)

However, if you want to let Ruby 1.9 stay smart about its transcoding while still providing backward compatibility, you will just need to write code for each version. Here’s an example of how this was done

if "".respond_to?(:encode!)
  def normalize_builtin_encoding(text)
    text.encode!("ISO-8859-1")
  end
else
  require 'iconv'
  def normalize_builtin_encoding(text)
    text.replace Iconv.conv('ISO-8859-1//TRANSLIT', 'utf-8', text)
  end
end
Sandheep
Posted by Sandheep to Sandheep's deck (2013-05-10 17:54)