Hi,

On Wed, 02 Jun 2004 14:26:18 +0200, Robert Klemme wrote:
>> I don't think that's the output he wanted.  He wanted
>> to have de value of %(name)s converted to a string,
>> and %(age)d to a number  (see my other post for an
>> implementation).
> 
> Quite easy to fix:
> 
> def myformat(str, hash)
>   str.gsub( %r{%\((\w+)\)(.)?} ) do
>     val = hash[$1]
> 
>     case $2
>       when 'd'
>         val.to_i
>       when nil, 's'
>         val.to_s
>       else
>         val
>     end
>   end
> end
> 
>>> myformat("My name is %(name)s and my age is %(age)d.", "name" => "Sam",
> "age" => 34)
> => "My name is Sam and my age is 34."
> 
> Or even more OO and in fact using less LOC:
> 
> CONV = Hash.new( lambda {|x| x} ).update( {
>   'd' => lambda {|x| x.to_i }
> } )
> 
> def myformat2(str, hash)
>   str.gsub( %r{%\((\w+)\)([dsi])?} ) { CONV[$2].call hash[$1] }
> end
> 
>>> myformat2("My name is %(name)s and my age is %(age)d.", "name" =>
> "Sam", "age" => 34)
> => "My name is Sam and my age is 34."
> 

That's nice, but unfortunately it doesn't take into account
octal numbers and the other hairy sprintf details:

(I borrowed the gsub block thing...)

def myformat3(str, format)
  arr = []
  str.gsub(/%\((.*?)\)/) { arr << format[$1]; "%" } % arr
end

Regards,
Kristof