From: "Hal E. Fulton" Date: 2001-12-30T08:51:30+09:00 Subject: [ruby-talk:29669] Re: comma-delimited to an array ----- Original Message ----- From: Dash Riprock Newsgroups: comp.lang.ruby To: ruby-talk ML ; Sent: Saturday, December 29, 2001 5:37 PM Subject: [ruby-talk:29668] comma-delimited to an array > I've got a file in which each line has comma-delimited items. A > sample might look like this: > > num,date,time,orig,type,action,rule,iface > 1,28Dec2001,23:59:51,121.210.49.22,log,accept,16,eth-s1p2c0 > 2,28Dec2001,23:59:44,121.210.48.11,log,drop,20,eth-s1p1c0 > 3,28Dec2001,23:59:57,121.210.49.22,log,accept,16,eth-s1p1c0 > > Because the order of the items may *vary* from day to day, I want to > treat each line as an array. > > But the question is, as I read each line, how do I convert that > single line into an array? Here's a quick and dirty way. It assumes 1) everything is a string and nothing has quotes on it yet (per your example) and 2) you don't mind using eval. arr = eval ("[" + line.chomp.split(",").collect {|x| '"' + x + '"'}.join(",") + "]") Warning: I haven't tested this. The translation for the newbie: - remove the newline - get an array of items delimited by commas - get another array consisting of all those same elements but surrounded by quotes - create a new string by joining using commas - surround the new string with brackets - eval to get an array of strings Hope this helps. Note that some people are really paranoid about eval. I think in a case like this, it's a non-issue. (Someone will probably prove me wrong.) Also note that the problem gets more complex if you start embedding commas and quotes inside the data items; if you want to treat some of them as integers or other things; and so on. Cheers, Hal Fulton