From: Robert Klemme Date: 2004-06-02T21:28:39+09:00 Subject: Re: What is the equivalent of Python's "%s" % "MyString"? "Kristof Bastiaensen" schrieb im Newsbeitrag news:pan.2004.06.02.10.45.26.409952@vleeuwen.org... > Hi, > > On Wed, 02 Jun 2004 08:47:30 +0200, Robert Klemme wrote: > > def myformat(str, hash) > > str.gsub( %r{%\((\w+)\)} ) {hash[$1]} > > end > > > >>> myformat("My name is %(name)s and my age is %(age)d.", "name" => "Sam", > > "age" => 34) > > => "My name is Sams and my age is 34d." > > 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." Regards robert