quick and dirty ruby

At work I received an email from someone that listed libraries I should use when connecting to their AS400 system. I wanted a quick way to convert their whitespace table into a nice comma-separated list. Below is the first 6 lines from about 50 or so.

Sequence
 number   Library
    10    QTEMP            

    20    DDMFLIB2
....

If it’s computable but a one-off, I immediately go to Ruby nowadays. 10 years ago it would have been Perl, 15 or 20 years ago the choice would have been probably a meld of sed|awk.

I always go with __END__ in these situations; Ruby stops processing at the __END__ line, but you are given an enumerable access to the contents that follow with the magical DATA object.

matches = DATA.collect { |line| line.match(/\\\\s+\\\\d+\\\\s+(\\\\w+)/) }
matches.compact!
puts matches.collect { |match| match[1] }.join(', ')

__END__
Initial library list:                            

Sequence
 number   Library
    10    QTEMP            

    20    DDMFLIB2
    30    APPSDEV
    50    FILES2                                                       

   110    QRPG                                                              

Let’s try it out (running Ruby/Windows in a Cygwin terminal):

dday@xpmachine21 ~
$ ruby liblist.rb
QTEMP, DDMFLIB2, APPSDEV, FILES2, QRPG

Success!

del.icio.us:quick and dirty ruby digg:quick and dirty ruby spurl:quick and dirty ruby wists:quick and dirty ruby simpy:quick and dirty ruby newsvine:quick and dirty ruby blinklist:quick and dirty ruby furl:quick and dirty ruby reddit:quick and dirty ruby fark:quick and dirty ruby blogmarks:quick and dirty ruby Y!:quick and dirty ruby smarking:quick and dirty ruby magnolia:quick and dirty ruby segnalo:quick and dirty ruby gifttagging:quick and dirty ruby

2 Responses to “quick and dirty ruby”

  1. Leslie Hensley Says:

    I liked the original version of this post better.

    puts DATA.collect{|line| $1 if line =~ /\s+\d+\s+(\w+)/}.compact.join(’, ‘)

    I’m normally not a fan of the $ but I think it is a good fit for this situation.

  2. darrend Says:

    Or:

    
    puts DATA.inject([]) { |matches,line| matches < < $1 if line =~ /\s+\d+\s+(\w+)/; matches }.join(', ')
    

Leave a Reply