3

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)?

7
  • 1
    So, you want to convert any leading and trailing single-quotes to double-quotes? Or all single-quotes to double-quotes? Commented Oct 12, 2011 at 15:48
  • Is the ' 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)? Commented Oct 12, 2011 at 15:49
  • No, quote is not a part of string. If you paste both strings into irb you can make idea what I need. Commented Oct 12, 2011 at 15:53
  • Then state more clearly what kind of transformation you want to perform on the string. Commented Oct 12, 2011 at 15:55
  • You are asking how to turn a 12-character string into a 3-character string, right? If so, great question! Commented Oct 12, 2011 at 15:55

2 Answers 2

3

Proposal:

s.gsub(/\\(\d{3})/) { $1.oct.chr }

It depends on what assumptions you can make about your input.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this is safer than eval solution.
1

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

Thanks! Don't like eval, but this is nice and short solution.

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.