Wednesday, December 12, 2007

stupid ruby trick #1

Here's why I like dynamic languages. I have a template (function) in an XSLT application that I invoke with the number of columns in an output table. The template then returns a list of integer values separated by carets "^".

Each integer is the width of a column as a percentage of the table width. The ideal width for each column depends on the size of the column header label and text in each row, which is a bit of a subjective fiddle, so I can't really automate setting the proportion of each column, at least not without doing some advanced parsing of the table data.

Of course, all the integers for a given number of columns are supposed to add up to 100 percent, and the list should have only as many integers as there are columns in the table. For tables with 5 or 6 columns, it's pretty easy to eyeball the sum, and make sure there's the right number of values, e.g. "10^20^20^30^20". When the tables get up to 14 or 15 columns, manually adding up all those column widths to 100 for the right number of columns becomes a PITB. Time for a little scripting!

So I whipped up this little one-liner in irb to do the math for me:


C:\USAFIPD\Tools\Reports>irb
>> n = "4^10^10^10^6^6^6^5^6^6^6^5^6^5^6^3"
=> "4^10^10^10^6^6^6^5^6^6^6^5^6^5^6^3"
>> eval(n.gsub("^","+"))
=> 100
>> puts "sum: " + eval(n.gsub("^","+")) + " cols: " + n.split("^").length
TypeError: can''t convert Fixnum into String
from (irb):3:in ''+''
from (irb):3
>> puts "sum: " + eval(n.gsub("^","+")).to_s + " cols: " + n.split("^").length.to_s
sum: 100 cols: 16
=> nil
>>


I made a couple of fumbles and educated guesses, based on my experience with Javascript and Perl, e.g. that eval(n.gsub(...)) would add up the digits. Still, I didn't have to refer to the Pickaxe Book at all!

I'll stick that into a .rb file for future use, passing in the list of column widths as an arg (once I remember how to get it from ARGV [or is it ARGS?!]). Gee, maybe I could put the body in a loop that keeps prompting me if the sum is not 100, so I can keep fiddling the string until it's right... hm...

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.