String interpolation in Ruby is a powerful feature that allows you to embed expressions directly within string literals. It provides a clean and efficient way to create dynamic strings, making your code more readable and maintainable.
To use string interpolation in Ruby, enclose the expression you want to embed within #{}
inside a double-quoted string. Ruby will evaluate the expression and convert the result to a string.
name = "Alice"
puts "Hello, #{name}!" # Output: Hello, Alice!
String interpolation isn't limited to simple variables. You can include method calls, mathematical operations, and even multi-line expressions.
age = 30
puts "In 5 years, I'll be #{age + 5} years old."
puts "The result is: #{
(1..5).map { |n| n * 2 }.join(', ')
}"
""
) for strings with interpolation.''
).String interpolation is often preferred over concatenation or the sprintf
method for its clarity and ease of use. However, for very complex formatting, you might consider using Ruby String Methods or the sprintf
method.
While string interpolation is generally efficient, for high-performance scenarios or when dealing with large amounts of data, you might want to benchmark it against alternatives like Ruby String Concatenation.
By mastering string interpolation, you'll write more elegant and expressive Ruby code. It's a fundamental technique that integrates well with other Ruby String Methods and Ruby Data Types.