5

I am having string str = "[123, 345, 567]". I want to convert this to an array arr = [123, 345, 567]. How to do this?

0

4 Answers 4

23

If you know that the string contains an array, you can just plain use eval;

arr = eval(str)

If you're not sure, you can go for the a bit more involved removing braces, splitting on , and collecting the numbers to an array;

arr = str[1..-2].split(',').collect! {|n| n.to_i}

Demo of both here.

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

1 Comment

Whoa there, cowboy! Not so fast. Eval is very dangerous. If str came from the evil interwebs, for instance as a param, your app could be running ANYTHING. Imagine a hacker changing that str param from "[123,456,789]" to "User.destroy_all". You're safer going with the second option and parse out the ids.
4
str = "[123, 345, 567]"

1) eval(str)

2) str = "[123, 345, 567]".scan( /\d+/ ) # Make the array
str.map!{ |s| s.to_i } # convert into integer

Comments

2

The simplest thing is something like arr = eval(str) but that's not very secure. Another option is to do something like arr = str.gsub(/\[|\]/,'').split(/,/).map(&:to_i) - remove the parentheses from the original string, split on commas and then convert the resulting string fragments to integers.

Comments

1

For Rails projects, I've found that the built-in ActiveSupport JSON decoder is a nice solution. Simply wrap the string in JSON, decode it, then return the new array:

def to_a(str)   
    wrapped_str = "{ \"wrapper\": #{str} }"

    ActiveSupport::JSON.decode(wrapped_str)['wrapper'] rescue str
end

str = '[1, 2, [3, [4, 5, true, "a", {"test": "whee"}]]]'
str_to_a = to_a(str)

This will return an array as long as the string is valid JSON. If decoding fails, the original string will be returned. Note that valid JSON in this case only pertains to the contents of the array - if the string array contains any hashes (here comes the caveat), all hash keys must be enclosed in double quotes. Also note that boolean values will only be casted to booleans if they are not enclosed in quotes.

Returning the original string on decoding failure allows conversion of strings only where it succeeds (leaving other strings unchanged). Alternatively, you could force everything to an array (or empty array) by using rescue [] instead.

Comments

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.