GOAL:
- Accept DSV strings where the delimiter may consist of more than one character
- Accept DSV strings where there are no embedded delimiters
- Output text with no modification to the source string other than aligning custom delimiter with optional padding
QUESTION:
- Anyone have a re-factor or stylistic enhancement or two?
CODE:
module DreftymacAddon
module String
### <region-fdef ddef="dsvpretty ;; lineup delims pretty print dsv text with lined up delimiters ">
def dsvpretty(delim=';;',padd='')
sout = ""
asizes = []
alines = self.to_s.split(/[\x0a\x0d]/)
alines.each{|currline|
currline.split(delim).each_with_index{|currfld,icc|
asizes[icc] = [asizes[icc].to_i,currfld.length].max()
}
}
alines.each{|currline|
next if currline.strip == ''
atemp = []
currline.split(delim).each_with_index{|currfld,icc|
atemp << sprintf("%-#{asizes[icc]}s", currfld)
}
sout += atemp.join([padd , delim , padd].join(''))
sout += "\n"
}
sout
end
alias :dsv_pretty :dsvpretty
### </region-fdef>
end
end
class String
include DreftymacAddon::String
end
### String.new().dsvpretty ;; example usage
##{
if(1000!=0);
vout = %Q[
LNAME|FNAME|AMOUNT|AGE|NATION|PLATFORM
Rodriguez|Johan|30.00|58|uk|windows_xp
Raynor|Coty|40.00|14|uk|redhat
Bruen|Jackie|30.00|17|uk|ubuntu
Breitenberg|Waldo|20.00|14|canada|mac_osx
Collier|Lucy|30.00|22|canada|windows_vista
Blick|Emmett|30.00|59|canada|knoppix
Schroeder|Myrtis|10.00|29|uk|knoppix
Rodriguez|Ashtyn|20.00|22|uk|mac_osx
Leuschke|Sigmund|40.00|21|france|redhat
Fahey|Cassidy|40.00|29|canada|knoppix
]
puts vout.dsvpretty('|','')
=begin
LNAME |FNAME |AMOUNT|AGE|NATION|PLATFORM
Rodriguez |Johan |30.00 |58 |uk |windows_xp
Raynor |Coty |40.00 |14 |uk |redhat
Bruen |Jackie |30.00 |17 |uk |ubuntu
Breitenberg|Waldo |20.00 |14 |canada|mac_osx
Collier |Lucy |30.00 |22 |canada|windows_vista
Blick |Emmett |30.00 |59 |canada|knoppix
Schroeder |Myrtis |10.00 |29 |uk |knoppix
Rodriguez |Ashtyn |20.00 |22 |uk |mac_osx
Leuschke |Sigmund|40.00 |21 |france|redhat
Fahey |Cassidy|40.00 |29 |canada|knoppix
=end
puts vout.dsvpretty('|',' ')
=begin
LNAME | FNAME | AMOUNT | AGE | NATION | PLATFORM
Rodriguez | Johan | 30.00 | 58 | uk | windows_xp
Raynor | Coty | 40.00 | 14 | uk | redhat
Bruen | Jackie | 30.00 | 17 | uk | ubuntu
Breitenberg | Waldo | 20.00 | 14 | canada | mac_osx
Collier | Lucy | 30.00 | 22 | canada | windows_vista
Blick | Emmett | 30.00 | 59 | canada | knoppix
Schroeder | Myrtis | 10.00 | 29 | uk | knoppix
Rodriguez | Ashtyn | 20.00 | 22 | uk | mac_osx
Leuschke | Sigmund | 40.00 | 21 | france | redhat
Fahey | Cassidy | 40.00 | 29 | canada | knoppix
=end
end
##}