String.force_encoding() in Ruby 1.8.7 (or Rails 2.x)

Solution 1:

This will give you String#to_my_utf8 in both Ruby 1.8.7 and Ruby 1.9:

require 'iconv'
class String
  def to_my_utf8
    ::Iconv.conv('UTF-8//IGNORE', 'UTF-8', self + ' ')[0..-2]
  end
end

And then...

?> "asdf".to_my_utf8
=> "asdf"

Inspired by Paul Battley and also remembering some of my older work on the remote_table gem.

Solution 2:

The only thing force_encoding does in 1.9 is that it changes the encoding field of the string, it does not actually modify the string's bytes.

Ruby 1.8 doesn't have the concept of string encodings, so force_encoding would be a no-op. You can add it yourself like this if you want to be able to run the same code in 1.8 and 1.9:

class String
  def force_encoding(enc)
    self
  end
end

There will of course be other things that you have to do to make encodings work the same across 1.8 and 1.9, since they handle this issue very differently.