From: William Crawford Date: 2006-09-01T00:20:39+09:00 Subject: Re: splitting string to hash Brian Nice wrote: > I have a strings like the following: > s1- "[1] Hello [2] bye" > s2- "[1] Hello [2] bye [2:1] continue [2] more" > > I want to convert them to hashes like > h1- {1 => "Hello", 2 => "bye"} > h2- {1 => "Hello", 2 => "bye", "2:1" => "continue", "2:2" => more"} > > Is there an easy Ruby way to do this? > Thanks for the help > Brian Assuming that James is correct in that :2 is missing from the second string, this works: h2 = Hash[*s2.scan(/\[([^\[\]]+)\] (\w+)/).flatten] (I'm starting to really like Ruby.) In case that's not clear, scan uses a regex to provide an array of 2-element arrays from the text. Then flatten makes it into a single array, then the * turns it into a list of just values, instead of an array. Then Hash[] turns each 2 values into a hash. -- Posted via http://www.ruby-forum.com/.