views:

910

answers:

4

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

+3  A: 

In a double-quoted string in Ruby, you can insert the result of a Ruby expression like this:

puts "Hi!  I'm #{name}, and I'm #{age} years old."

Just put an expression inside the curly braces. (It could also be something more complex like #{age + 5}, or #{name + ' ' + last_name}, or a function call.)

yjerem
+1  A: 

puts "Hi! I'm #{name}, and I'm #{age} years old."

Chris Bunch
+4  A: 

There are some nice trick to this in Ruby:

name = "Peter"
@age = 15 # instance variable
puts "Hi, you are #{name} and your age is #@age"
Honza
+1  A: 
 class Template

  def %(h)
    "Hi!  I'm #{h[:name]}s, and I'm #{h[:age]}d years old."


  end
end

Then call it with

t=Template.new
t%({:name => "Peter", :age => 18})

This is not exactly what you asked for but could give you a hint.

Jonke