How to convert string into Array

ruby-on-rails-3.1

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

Best Solution

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.

Related Question