"Kristof Bastiaensen" <kristof / vleeuwen.org> schrieb im Newsbeitrag
news:pan.2004.06.02.17.33.01.599239 / vleeuwen.org...
> 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:

Wasn't meant to be a complete impl.

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

That looks nice!  Now we just need inject() like behavior for gsub - then we
can save one more line. :-)

....

We can save one step of substitution anyway:

def myformat4(str, hash)
  str.gsub( %r{%\((\w+)\)([dsi])?} ) { "%#{$2}" % hash[$1] }
end

Note: I didn't bother to look up all legal formatting characters.
Alternatively use [a-z] instead of [dsi].  And we can throw the last "?" out
if we require a formatting char like sprintf et al do.

This is not only cleaner but also more efficient I'd guess.  (Didn't
benchmark though.)  In fact, it looks like the most natural implementation
to me.

Thanks for the nice sparring!

Kind regards

    robert