0

I have a string that is URL encoded:

a = "%5B%22552A8619-6ECA-4A95-A798-C1E2CE75BFFF%22%2C%2264c19b5b2d0257ddb382dbd3660de3fd%22%2C%22share%22%5D"

If I URL decode this string then it will look like:

"[\"552A8619-6ECA-4A95-A798-C1E2CE75BFFF\",\"64c19b5b2d0257ddb382dbd3660de3fd\",\"share\"]"

From this string I want to get this array:

["552A8619-6ECA-4A95-A798-C1E2CE75BFFF","64c19b5b2d0257ddb382dbd3660de3fd","share"]

How to do that without nasty string replacements?

1
  • Where are you getting the string? Is it the result of some sort of a HTTP request? And, could that string be actually a JSON string? Commented Jan 22, 2013 at 22:39

4 Answers 4

3
the_given_string.scan(/"(.*?)"/).flatten
Sign up to request clarification or add additional context in comments.

2 Comments

While all other answers were correct, but I selected this because it looks very terse and works. By the way, I dont require to pass argument 1 in flatten
@JVK I had thought that providing the maximum depth to flatten improves the performance, but lost confidence. I just asked a question about it.
3

The string is an array encoded using JSON:

require 'cgi'
require 'json'

a = "%5B%22552A8619-6ECA-4A95-A798-C1E2CE75BFFF%22%2C%2264c19b5b2d0257ddb382dbd3660de3fd%22%2C%22share%22%5D"

JSON[CGI::unescape(a)]

[
    [0] "552A8619-6ECA-4A95-A798-C1E2CE75BFFF",
    [1] "64c19b5b2d0257ddb382dbd3660de3fd",
    [2] "share"
]

JSON[CGI::unescape(a)].last will return "share", putting you home free.

CGI::escape is used to remove the encoding, which turns it back to a "normal" JSON-encoded array.

JSON[] (AKA JSON.parse) converts it from the JSON notation back to a Ruby array.

Comments

2

You could delete characters and split, or evaluate it:

"[\"A798-C1E2CE75BFFF\",\"643fd\",\"share\"]".delete('\"[]').split(',')
# => ["A798-C1E2CE75BFFF", "643fd", "share"]

eval "[\"A798-C1E2CE75BFFF\",\"643fd\",\"share\"]"
# => ["A798-C1E2CE75BFFF", "643fd", "share"]

1 Comment

Thank you. But eval being crazy, I am hesitant to use it. First answer works.
1

You could eval the string:

require 'cgi'
a = "%5B%22552A8619-6ECA-4A95-A798-C1E2CE75BFFF%22%2C%2264c19b5b2d0257ddb382dbd3660de3fd%22%2C%22share%22%5D"
x = eval( CGI.unescape(a))
p x #["552A8619-6ECA-4A95-A798-C1E2CE75BFFF", "64c19b5b2d0257ddb382dbd3660de3fd", "share"]

But eval is evil.

You could use , what you call nasty string replacement:

p CGI.unescape(a).gsub(/\A\["|"\]\Z/,'').split(/","/)

Or you could try JSON:

require 'cgi'
require 'json'
a = "%5B%22552A8619-6ECA-4A95-A798-C1E2CE75BFFF%22%2C%2264c19b5b2d0257ddb382dbd3660de3fd%22%2C%22share%22%5D"
x = JSON.load( CGI.unescape(a))

1 Comment

Thank you. You have a very comprehensive answer :)

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.