From: Kristof Bastiaensen Date: 2004-06-02T09:03:38+09:00 Subject: Re: What is the equivalent of Python's "%s" % "MyString"? Hi, On Tue, 01 Jun 2004 18:38:32 +0000, Sam Sungshik Kong wrote: > Hello! > > I am studying Ruby and have been using Python. Good! > 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) > This is almost identical in ruby: "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} > > or > > format = "My name is %(name)s and my age is %(age)d." > di = {"name": "Sam", "age": 34} > s = format % di > > > I know that ruby has "#{name}" expression. > But that requires a variable named "name" in advance. > I want to bind the format string and data later. > What is the closest thing in ruby? > I find the python expression quite useful. I don't think Ruby supports this from itself. Personally I find that #{} is enough in most cases. If you really need this, you could define it with the following code: class String alias :old_percent :% def %(format) return old_percent(format) if not format.is_a? Hash arr = [] str = self while (match = /%\((.*?)\)/.match(str)) str = match.post_match arr << format[match[1]] end self.gsub(/%\(.*?\)/, "%").old_percent(arr) end end "My name is %(name)s and my age is %(age)d." % {"name" => "Sam", "age" => 34} Regards, Kristof