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

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.

Leave a Comment