1

i have in database a string like \303\255 which represents í .

How can i convert that 8 chars representation in í ?

I could replace them all, but isn't there any other way ?

2
  • Do you mean you have the string: str = "\"\\303\\255\"" (i.e. the slashes really are in the string?). You'll have to extract them and Array#pack them into real characters if they are. Commented Sep 29, 2011 at 12:27
  • Do you have the problem with Ruby 1.8.x or Ruby 1.9.x? In 1.9.x, the solution of @JonasElfström should be sufficient. Commented Sep 29, 2011 at 13:07

2 Answers 2

1

It's not really 8 characters in the string, it's 2 bytes. I'm not sure where you want \303\255 to show up as í but if you put

# encoding: utf-8

in the top of your .rb-file Ruby will use UTF-8.

If you are using Ruby on Rails you can try to add the following two lines to config/environment.rb

Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming the problem really is as you describe, and not just a misunderstanding.

I battled with this. It's not pretty. This parses the string and uses pack to pack down the relevant bytes.

"foo \\303\\255 bar".gsub(/(\\\d{3})+/) do |match|
  match[1..-1].split("\\").map{ |octet| octet.to_i(8) }.pack("c*")
end.force_encoding("UTF-8")

The much shorter version uses eval, but it's always worth trying to avoid eval if you can, since it has huge security risks if used incorrectly. Given that we're validating the format of what we're eval'ing here, I'll go ahead and say it's probably safe to do this:

"foo \\303\\255 bar".gsub(/(\\\d{3})+/) { |m| eval('"' + m + '"') }

3 Comments

The eval is working! Will check why the first os not working... Thanks a lot man! :D
Make sure you only eval the bits of the string you know are safe, otherwise (if you could find yourself in a mess). My code is ok, but eval'ing the entire string, while it would likely work, would be dangerous.
This is internal and private data transformation so it's ok to use eval on this, but thanks for the warning!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.