Parsing pipe delimited text file & storing in arrays

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]

On Jun 6, 2012, at 7:03 PM, ideal one [email protected] wrote:


Posted via http://www.ruby-forum.com/.

Why are you splitting on commas when your delimiter is a pipe?

On 07/06/12 13:03, ideal one wrote:

(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

Hi,

Personally, I’d loop over each line of the file (see “gets”), and you’re
probably going to want your argument to “split” to be a pipe ("|")
rather than a comma (","). I would avoid complex expressions, opting
instead to break things up into simpler steps, until you are more
comfortable with the environment.

I hope this helps. Good luck! :slight_smile:

Garthy