From: Josef 'Jupp' SCHUGT Date: 2003-10-13T04:46:47+09:00 Subject: Re: splitting a line by columns Hi! * Mike Campbell; 2003-10-12, 11:44 UTC: > I have a line of text output in columnar form; what's the best way > to split it into its requisite parts? That's one of those 'it only takes n programmers to get n+1 results' qestions. It strongly depends on what you mean by 'best way'. > Say I have lines of > > aaaaabbcccccddeee > > I can do something like: > > md = /(.....)(..)(.....)(..)(...)/.match(line); # seems klugy somehow > > Thoughts? Here are mine: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #!/usr/bin/env ruby class Cutter < Array def cut(line) map { |range| line[range] } end end knife = Cutter.new([0..4, 5..6, 7..11, 12..13, 14..16]) md = knife.cut(line) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - I am a bit surprised how powerful that ad hoc solution is: It supports overlapping columns and columns can be arranged in arbitrary order, ... The solution also makes it easy to programmatically select the columns of interest before cutting anything: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - knife = Cutter.new() knife.push(0..4) if rand < 0.5 knife.push(5..6) if rand < 0.5 knife.push(7..11) if rand < 0.5 knife.push(12..13) if rand < 0.5 knife.push(14..16) if rand < 0.5 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Comments? Please take notice of signature! / Bitte Signature beachten! Josef 'Jupp' Schugt -- db Wenn sie mir ohne meine Einwilligung geschickt wurde, db dpqb wird eine E-Mail > 100 kB ungelesen entsorgt dpqb dp::qb If you send me an e-mail > 100 kB without my dp::qb dp::::qb consent it will be silently discarded dp::::qb