On Feb 28, 2008, at 11:57 AM, Trans wrote:
I have a question and perhaps a bit of challenge for those with mad
parse skills: Has anyone ever considered named parameters for sprintf/
printf? It would be quite useful (to me at least) to be able to do:
“I am %(name)s.” % { :name => “Tom” ]
Has anyone worked on something like this before? Is there anything
equivalent in the Perl world or other language?
I released a gem last year (http://jig.rubyforge.com) that defines
a data structure I nicknamed a Jig that enables this sort of thing
either by parsing a string to get the format or by explicit
construction:
j = Jig.new('I am ', :name)
j2 = Jig.parse(‘I am %{:name:}’)
puts j % { :name => ‘Tom’} # I am Tom
puts j2 % { :name => ‘Alice’} # I am Alice
A Jig is a ordered sequence of objects and ‘gaps’. Simple gaps are
identified as symbols during Jig construction but you can also define
gaps that process anything that is used to fill them:
capitalize = Jig::Gap.new(:name) { |x| x.capitalize }
j2 = Jig.new('before: ', :name, ’ after: ', capitalize)
puts j2 % {:name => ‘bob’ } # ‘before: bob after: Bob’
In that example you can see that all gaps with the same name
are plugged simultaneously. Unplugged gaps are rendered as
the empty string when Jig#to_s is called.
You can also construct a Jig or fill a gap with a proc/lambda/method
which will be evaluated at the time the Jig is rendered to a string:
time = Jig.new("The time is ") {Time.now}
puts time # The time is Thu Feb 28 18:16:07 -0500 2008
sleep 5
puts time # The time is Thu Feb 28 18:16:12 -0500 2008
The gem has classes for handling XML, XHTML, and CSS constructs.
I’ve made a few changes since the initialize release but haven’t
gotten around to pushing it a new release to Rubyforge yet…
Gary W.
http://jig.rubyforge.com