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>

Latest News
icalendar 1.4.0 Released
    Ryan Ahearn - 2013-05-21 23:17
BinData 1.5.0 - source moved to github
    Dion Mendel - 2013-05-21 11:10
v13.5.0 Released !!
    id 774 - 2013-05-18 12:28
Runt v0.9.0 Released
    Matthew Lipper - 2013-05-17 00:11
kramdown 1.0.2 released
    Thomas Leitner - 2013-05-09 06:58

 

Forums | Admin

Discussion Forums: stringformat---customizable-string-formats

Start New Thread Start New Thread

 

Topic Topic Starter Replies Last Post