开发者

Ruby string representation

开发者 https://www.devze.com 2023-04-09 01:34 出处:网络
i have in database a string like \\303\\255 which represents í . How开发者_运维问答 can i convert that 8 chars representation in í ?

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 ?


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


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 + '"') }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号