JVK
JVK

Reputation: 3912

Ruby string to array conversion

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?

Upvotes: 0

Views: 658

Answers (4)

the Tin Man
the Tin Man

Reputation: 160621

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.

Upvotes: 3

sawa
sawa

Reputation: 168259

the_given_string.scan(/"(.*?)"/).flatten

Upvotes: 3

knut
knut

Reputation: 27885

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

Upvotes: 1

AJcodez
AJcodez

Reputation: 34236

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"]

Upvotes: 2

Related Questions