Lets say we have the string '\342\200\231' (same as "\\342\\200\\231"). What is a quick way to convert this string to "\342\200\231" (same as ’ Unicode character)?
2 Answers
Proposal:
s.gsub(/\\(\d{3})/) { $1.oct.chr }
It depends on what assumptions you can make about your input.
1 Comment
taro
Thanks, this is safer than eval solution.
What you appear to be asking is how to change a 12-character string into a three-character string.
'\342\200\231'
is 12 characters long.
"\342\200\231"
is three characters long; actually three bytes long, but in Ruby 1.8 it is about the same since strings are sequences of bytes anyway.
Here is an EVIL answer for you (you did say quick), which takes advantage of eval to do your "parsing":
irb(main):017:0> s = '\342\200\231'
=> "\\342\\200\\231"
irb(main):018:0> t = eval('"' + s + '"')
=> "\342\200\231"
irb(main):019:0> s.length
=> 12
irb(main):020:0> t.length
=> 3
Sorry for the eval!
I should probably give a more helpful answer... EDIT: Someone else just did.
1 Comment
taro
Thanks! Don't like eval, but this is nice and short solution.
'part of the actual string? Or are you trying to convert a single-quoted string into a double-quoted string (they're both the same thing, aside from double-quoted strings allowing more things like interpolation)?