From: "rmagick@..." Date: 2007-03-24T07:50:05+09:00 Subject: Re: How to Convert String to Array On Mar 23, 6:36 pm, Shengzhi Li wrote: > Hey everyone, > > Newb question: I want to read the user input an array of numbers. Is > this possible? If not, then I want to convert the string input (from > gets) into an array. > > For example: > > user inputs [5,3,46,6,5] > gets.chomp converts this to a string "[5,3,46,6,5]" > I want [5,3,46,6,5] (the arrray, not the string) > > Any help would be greatly appreciated. > > Thanks, > > ~sphoenixee~ > > -- > Posted viahttp://www.ruby-forum.com/. irb(main):017:0> x = '[5,3,46,6,5]' => "[5,3,46,6,5]" irb(main):018:0> y = x[1..-2].split(',').collect! {|n| n.to_i} => [5, 3, 46, 6, 5] irb(main):019:0> 1. x[1..-2] is the string without the brackets. 2. split(',') splits the string at commas into an array of strings. 3. collect! calls .to_i on each string in the array and replaces the string with the result of the conversion.