Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string into Array

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

like image 862
Achaius Avatar asked Apr 03 '12 11:04

Achaius


2 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.

like image 137
Joachim Isaksson Avatar answered Oct 13 '22 21:10

Joachim Isaksson


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
like image 22
Vik Avatar answered Oct 13 '22 20:10

Vik