From: Sam Duncan Date: 2012-06-07T12:06:52+09:00 Subject: Re: Parsing pipe delimited text file & storing in arrays On 07/06/12 13:03, ideal one wrote: > Hi, > I have a txt file with pipe delimited as show below. > > An example log file is: > test1|table1|chair1|55.00 > test2|table2|chair2|155.00 > test3|table3|chair3|55.50 > test1|table4|chair4|47.75 > > i want to parse this txt file and my expected out should be > > (i) Total Cost of test1 = 55.00 + 47.75 > (ii) test1 possessed chair1 and chair4 > > How do i achieve this in ruby code, i tried but doing it as array but > how can i add up the price what 'test1' is responsible to pay? > > array = File.read("pipetest.txt").split(",").map(&:strip) > > puts array[1,2] > > irb 1.9.3p125 :001 > foo = "test1|table1|chair1|55.00\ntest2|table2|chair2|155.00\ntest3|table3|chair3|55.50\ntest1|table4|chair4|47.75" => "test1|table1|chair1|55.00\ntest2|table2|chair2|155.00\ntest3|table3|chair3|55.50\ntest1|table4|chair4|47.75" 1.9.3p125 :002 > tests = Hash.new { |h, k| h[k] = [] } => {} 1.9.3p125 :003 > foo.split("\n").each { |record| name, table, chair, price = record.split("|"); tests[name].push [chair, price] } => ["test1|table1|chair1|55.00", "test2|table2|chair2|155.00", "test3|table3|chair3|55.50", "test1|table4|chair4|47.75"] 1.9.3p125 :004 > tests.each_pair { |test, data| puts "(i) Total Cost of #{test} = " << (data.collect { |entry| entry.last }).join(" + "); puts "(ii) #{test} possessed " << (data.collect { |entry| entry.first }).join(" and ") } (i) Total Cost of test1 = 55.00 + 47.75 (ii) test1 possessed chair1 and chair4 (i) Total Cost of test2 = 155.00 (ii) test2 possessed chair2 (i) Total Cost of test3 = 55.50 (ii) test3 possessed chair3 => {"test1"=>[["chair1", "55.00"], ["chair4", "47.75"]], "test2"=>[["chair2", "155.00"]], "test3"=>[["chair3", "55.50"]]} That was a bit of fun. I'm sure you could do a better job of it if you spent a few more minutes =] Sam