From: "Guy N. Hurst" Date: 2002-04-14T19:01:56+09:00 Subject: RCR: key value mapping for sprintf/% I was on irc at irc.openprojects.net in #ruby-lang last week when someone came in and asked if Ruby had something like python's string formatting templates. While we were able to refer him to various templating/interpolating solutions, they didn't solve his problem as directly as he expected. After some discussion, we realized what he was asking. Python allows you to pass a mapping (e.g. Hash) as values to a format string. (cf. http://www.python.org/doc/current/lib/typesseq-strings.html) In Ruby, we have format strings, but they only accept a fixed number of arguments, and are substituted in the order they are provided. "This is first: %s, and this is 2nd: %s" % ['one','two'] But python allows something like this for the format string: ftext = "%(name)s is %(gender)s. %(name)s is %(age)2d years old" In Ruby, it might work like this: hash = {'gender'=>"male", 'name'=>"Fred", 'age'=>23} ftext % hash # "Fred is male. Fred is 23 years old" I wrote a substitute method for String#% which treats a Hash argument as described above. It seems to be working fine, and I even posted it to the RAA ("TextFormatTemplate"). However, it seems this is something that could (should?) be easily added to Ruby itself. It would help those coming from Python, add a useful feature, and be totally backwards-compatible. http://www.ruby-lang.org/en/raa-list.rhtml?name=TextFormatTemplate Guy N. Hurst