From: Rajinder Yadav Date: 2009-12-27T02:03:47+09:00 Subject: Re: How to parse this file Simone D'Amico wrote: > Hello guys, > I have to parse a file of questions/answers for a quizbot in ruby. > The file is structured in this way: > "Question" "Answer"\r\n > "Question2" "Answer2"\r\n > "Questionn" "Answern"\r\n > > How to parse it efficacely? > Thank you in advance. > > Simone D'Amico > *nix powered > sim@me.com > here is the basic code, output followed by a basic explanation IO.foreach("testfile.txt") do |line| data=line.match /\"(\w+)\"\s+\"(\w+)\"/ puts data[1] # question puts data[2] # answer end [output] Question Answer Question2 Answer2 Questionn Answern basic explanation: match returns a MatchData object, which can be accessed like an array. you will want to access the 2nd and 3rd position of the MatchData object, the first (zero position) holds an array of the entire parsed data set. irb(main):337:0> str='"Question" "Answer"' irb(main):338:0> data=str.match /\"(\w+)\"\s+\"(\w+)\"/ irb(main):339:0> data[0] => "\"Question\" \"Answer\"" irb(main):340:0> data[1] => "Question" irb(main):341:0> data[2] => "Answer" -- Kind Regards, Rajinder Yadav http://DevMentor.org Do Good! - Share Freely