I am having string str = "[123, 345, 567]". I want to convert this to an array arr = [123, 345, 567]. How to do this?
4 Answers
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.
1 Comment
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
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.