From: Jonathan Gillette Date: 2002-03-30T05:13:56+09:00 Subject: My sprintf methods and props for FXRuby I've had a blast with Ruby over the past seven or so months and thought I'd pass on a bit of favorite code. I always find myself laying out my strings with sprintf and found it handy to add sprintf methods to arrays, hashes, and the REXML::Element class. I thought someone else might find this useful or might clue me in on some optimizations. # The Array#sjoin is similar to Array#join in that it creates a string # containing the elements in order, but sjoin allows a format string, # so # ['talby','boiler','doolittle','pinback'].sjoin( "(%s)", "," ) # => (talby),(boiler),(doolittle),(pinback) class Array def sjoin( fmt, sep ) collect { |x| Kernel::sprintf( fmt, x ) }.join( sep ) end end # Hash#sprintf will take a format string, then keys for each value to be used # test_hash = { 'name' => 'joe', 'relationship' => 'mom' } # test_hash.sprintf( '%s is my %s', 'name', 'relationship' ) # => 'joe is my mom' class Hash def sprintf( *args ) if args == []; return; end eval "return Kernel::sprintf( '" + args.shift + "', " + args.sjoin( "@elements[ '%s' ].text.strip()", ", " ) + " )" end end # Takes a format string then a list of XPath expressions # root.sprintf( "%s is my %s", "person/name", "person/relationship" ) require 'rexml/document' include REXML class Element def sprintf( *args ) if args == []; return; end eval "return Kernel::sprintf( '" + args.shift + "', " + args.sjoin( "@elements[ '%s' ].text.strip()", ", " ) + " )" end end That last one is sort of weak with the Element#text.strip() part if text is nil. I often check for the existence of the elements before using sprintf() anyway. Big props to the FXRuby team. I've had such fun with the whole module. I've been working on a debugger for web applications over UDP [http://www.javuh.com/psychoo/screens/buggoo-freebsd.jpg]. Adding tabs, tables, input controls is a breeze. Can't wait for threads to work with FOX on Windows. Nice work overall though. -- Jonathan Gillette iNetZ Media (801) 415-2566