I am having string str = "[123, 345, 567]". I want to convert this to an array arr = [123, 345, 567]. How to do this?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With