Posted By: Erik Hollensbe
Date: 2007-09-07 07:49
Summary: StringFormat - Customizable String Formats
Project: NGS Lib
StringFormat: A string format library that's programmable.
Synopsis:
# up-front interface
f = StringFormat.new(
"d" => proc { |item, num| num + ' ' + item } # %0.2d
"s" => proc { |item, num| item } # %s
)
s = f.new_string "my_string %s"
# StringFormat is just a subclass of String, so this works:
s % "hello there" # => "my_string hello there"
# something more complex (using base-class String methods):
s[s.length - 2 .. s.length - 1] % "something new" # => "something new"
# add iteratively -- works with generated Format#new_string objects as well
f.add_format("f") do |item, num|
num + ' ' + item
end
f.del_format("d")
# add a format that does not require an argument:
f.add_format("e") do
Date.new.strftime("%s")
end
# and use it like such:
s = f.clone("string %e %f")
s % [1.2] => "string 12345667787 1.2"
s = f.clone("string %e")
s % nil => "string 12345667787"
# these also work on the string objects themselves, so you can add on for specific strings:
s.add_format("s") do |item, num|
"monkeys around"
end
s % "foobar" # => "my_string monkeys around"
An improperly formatted string (one that is passed too many or too little
arguments for what is expected) will raise a StringFormat::FormatError
exception.
Author: Erik Hollensbe <erik@hollensbe.org> |
|