"Michael Neumann" <mneumann / ntecs.de> schrieb im Newsbeitrag
news:20040601185436.GA19522 / miya.intranet.ntecs.de...
> On Wed, Jun 02, 2004 at 03:43:42AM +0900, Sam Sungshik Kong wrote:
> > Hello!
> >
> > I am studying Ruby and have been using Python.
> > I apologize for my negligence not to check out the whole document first.
> > What is the equivalent of the following Python's expressions?
> >
> > s = "My name is %s and my age is %d." % ("Sam", 34)
>
>   s = "My name is %s and my age is %d." % ["Sam", 34]
>
> > or
> >
> > s = "My name is %(name)s and my age is %(age)d." % {"name": "Sam",
"age":
> > 34}
>
> No direct equivalent in Ruby, but easy to implement:
>
>   def myformat(str, hash)
>     hash.each do |k,v|
>       str = str.gsub("%(#{k})", v)
>     end
>     str
>   end
>
>   s = myformat("My name is %(name)s and my age is %(age)d.", "name" =>
"Sam", "age" => 34)

May I just add a simple performance optimization?

def myformat(str, hash)
  str = str.dup
  hash.each do |k,v|
    str.gsub!("%(#{k})", v)
  end
  str
end

This saves you a lot intermediate strings that are thrown away immediately.

But I like this even more, since it needs less lines:

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."

Regards

    robert