You can use variables inside a Ruby string in the following ways:
- Using String Interpolation;
- Using Format Specifiers;
- Using Named Arguments;
- Using String Concatenation;
Using String Interpolation
You can use string interpolation (or variable substitution) in the following way:
name = "John" age = 22 puts "#{name} is #{age} years old!" # output: "John is 22 years old"
The variables (specified in #{}
) are expanded into their corresponding values in the resulting string.
Please note that string interpolation only works inside a double quoted string.
Using Format Specifiers
Similar to the sprintf
function, you can format a string by using "format specifiers" (i.e. field type characters prefixed with %
, that specify how their corresponding substitution arguments should be interpreted). For example, you can use the %s
format specification to indicate that its corresponding argument should be interpreted as a string in the following way:
color = "blue" puts "I love %s color!" % color # output: "I love blue color!"
You can use as many format specifiers in a string as you want. However, when the format specification contains more than one substitution, then the arguments should be specified as an Array
containing the values to be substituted. For example:
name = "John" age = 22 puts "%s is %d years old" % [name, age] # output: "John is 22 years old"
As you can see from the example above, the two format specifiers (%s
for string and %d
for decimal number) are substituted with their corresponding arguments as specified in the array after the %
sign.
Using Named Arguments
You can specify named arguments in the string with their corresponding substitution arguments in a Hash
like so:
name = "John" age = 22 puts "%{a} is %{b} years old" % {a: name, b: age} # output: "John is 22 years old"
Using String Concatenation
You can use the +
operator to join variables and parts of string together. For example:
color = "blue" puts "I love " + color + " color!" # output: "I love blue color!"
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.