In Python, you can do this:
print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30})
What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.)
EDIT: One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so:
template = "Hi! I'm %(name)s, and I'm %(age)d years old."
def greet(template,name,age):
print template % ({"name":name,"age":age})
This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's "Hi! I'm #{name}"
convention is cursorily similar, but the immediate evaluation makes it less versatile.
Please don't downvote answers suggesting the #{var}
technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)