String interpolation is the process of converting placeholders inside a string to the values they represent, in order to produce a dynamic string. You probably use it all the time without realizing just how cool it works under the hood, and how you can leverage this power in your own classes.
I came from a Perl environment, where variables look like $variable, and so string interpolation was pretty simple:
$person = 'World' print "Hello, $person!" # prints "Hello, World!"
Perl just recognized any alphanumeric word starting with a dollar sign as a variable, and replaced it inline. Ruby variables don’t start with a dollar sign though, so it’s a little more typing. Here’s how you include variables:
person = 'World'
puts "Hello, #{person}!" # prints "Hello, World!"
Ruby uses the idiom #{} to denote something that needs to be interpreted. But this extra typing comes with a huge benefit. You can include more than just strings, you can include entire expressions! Say our variable isn’t already capitalized, and we want to do that inline:
person = 'world'
puts "Hello, #{person.capitalize}!" # prints "Hello, World!"
Ruby will run the code inside the braces, and display that. But it gets even better: Ruby will interpret any type of expression, and convert it to a string for you:
puts "4 = #{4}" # prints "4 = 4"
puts "2 + 2 = #{2+2}" # prints "2 + 2 = 4"
Even if the code inside the braces isn’t a string, Ruby will convert inline. How does it do this? It calls the to_s method on the result of the expression. The expression 2 + 2 equates to 4, which is a Fixnum object. This object, like every other in Ruby, has a to_s method.
Another big benefit of this is that you can decide how your own objects will be displayed in strings. Let’s say you have a user class:
class User
attr_accessor :first_name, :last_name
def initialize first, last
self.first_name = first
self.last_name = last
end
def to_s
"#{first_name} #{last_name}"
end
end
We’ve just told Ruby that when our user object is converted to a string, we want it to show the full name (first and last). Let’s try it out:
user = User.new 'Jaime', 'Bellmyer'
puts "Hello, #{user}!" # prints "Hello, Jaime Bellmyer!"
This is one of many instances where knowing how ruby handles things under the hood can allow you create powerful code of your own. Enjoy!
Tags: class, fixnum, interpolation, object, perl, Ruby, string, to_s
