Ruby string substitution

You can use something called string interpolation in Ruby to accomplish this.

ex:

num1 = 4  
num2 = 2  
puts "Lucky numbers: #{num1} #{num2}";

Here each variable that is inside the #{} is interpreted not as a String but as a variable name and the value is substituted.


You can also use a hash for string substitution. This is useful if you have multiple instances that need be replaced with the same string.

p "%{foo} == %{foo}" % {:foo => "bar" }
# => "bar == bar"

num1 = 4  
num2 = 2  
print "Lucky numbers: %d %d" % [num1, num2]

n1, n2 = 17, 42
puts "Lucky single number: %d" % n1
puts "Lucky multiple numbers: %d %d" % [ n1, n2 ]
puts "Lucky inline interpolation: #{n1} #{n2}"

For documentation of the formatting allowed in String#% method read up on Kernel#sprintf.

Tags:

Ruby