How to parse text file in Ruby on Rails -
below text file:
old count: 56 s id: 1 m id: 1 new count: 2 old count: 56 s id: 1 m id: 2 new count: 20 old count: 56 s id: 1 m id: 2 new count: 32 ----------------------------- old count: 2 s id: 2 m id: 1 new count: 4 -------------------------------- . . . .
i have used delimiter "---------------" each ids.
how parse value such lines in delimiter "-----" new count added this: 2+20+32 = 54
hash array: count << {'new count' => 54}
first block , on remaining blocks.
i have tried this..
begin f=file.open("out2", "r") f.each_line |line| @data+=line end s_rec=@data.split("------") s_rec.each |rec| row_s=rec.split(/\n/) row_s.each |row| if r.include?"new count" rv=row.split(":") @db=rv[1] end end end
not sure output format trying achieve, given text:
text = <<__ old count: 56 s id: 1 m id: 1 new count: 2 old count: 56 s id: 1 m id: 2 new count: 20 old count: 56 s id: 1 m id: 2 new count: 32 ----------------------------- old count: 2 s id: 2 m id: 1 new count: 4 -------------------------------- . . . . __
this:
text .split(/^-{5,}/) .map{|s| s.scan(/\bnew count: (\d+)/).map{|match| match.first.to_i}.inject(:+)}
gives:
[ 54, 4, nil ]
in response comment, still not clear want because wrote not valid ruby object, this:
text .scan(/^s id: (\d+).+?^new count: (\d+)/m) .inject(hash.new(0)){|h, (k, v)| h[k.to_i] += v.to_i; h} .map{|k, v| {"s id" => k, "new count" => v}}
gives:
[ { "s id" => 1, "new count" => 54 }, { "s id" => 2, "new count" => 4 } ]
Comments
Post a Comment