8

I received the following error upon saving a new contact. Is there a way to cast "\xC2" so that it can be forced to be saved in the UTF-8 format?

c = Contact.new
c.save!

Encoding::UndefinedConversionError: "\xC2" from ASCII-8BIT to UTF-8: INSERT INTO "contacts" ("body", "created_at", "email", "updated_at") VALUES (?, ?, ?, ?)

sawa
  • 165,429
  • 45
  • 277
  • 381
Jackson Henley
  • 1,531
  • 2
  • 15
  • 27

2 Answers2

22

Your string is in some other encoding, most likely iso-8859-1, so you should run this to convert it:

"\xC2".encode("iso-8859-1").force_encoding("utf-8")
=> "Ã"

See this question for more information related to this issue.

Community
  • 1
  • 1
jvperrin
  • 3,368
  • 1
  • 23
  • 33
  • Was flailing around converting some code that used HtmlEntities from 1.8.7 to 1.9.3 — This helped. Thanks! – Subimage Dec 28 '13 at 09:28
4

For what it's worth, I had this issue pop up when I read in a code file that had the degree symbol (°) in a comment. Upon encoding it for json, ruby became incredibly unhappy.

What threw me for a loop was that there wasn't a "Ã" character in the code, so it's just something to keep in mind.

xavdid
  • 5,092
  • 3
  • 20
  • 32