8. Operations And Interpolations

In The Basics, we talked about operators. In the previous lesson, we went over how to assign values to a variable. In this lesson, we’ll learn how to combine the two.

Note: You’ve got to be sick of the phrase “save it and run it” by now, right? It is getting a little old, isn’t it? So from now on, when we say to write and try some code, we’ll expect that you’re creating a new file and executing it from the command line. We know you’ve got this down by now!

Simple Operations

If you wanted to display the result of math problem – like addition – to the CLI, how would you do it? You’d do it like this:

puts 3 + 2 

This will display 5 in your CLI – we’re telling Ruby to display the text value of 3 + 2, which is 5.

Now, try to predict what will happen if we write the following program:

puts '3' + '2' 

Try it for yourself. Why was 32 displayed in the CLI instead of 5? Because we told Ruby to add two strings together – not integers. Using the + sign on strings is the concatenation operator. This is the same sort of thing as if we had written puts 'hello ' + 'world' to produce hello world.

Let’s try something a bit more tricky. Write the following program:

# Trying to add a string and an integer puts '3' + 2 

You get an error, right? Look closely at the error message:

no implicit conversion of Fixnum into String (TypeError) 

This is telling us that Ruby can’t implicitly convert a number to a string and doesn’t know what to do other than throw a TypeError message.

Of course, it’s not really clear for us either: as programmers, what did we really want here? Did we want the math result of 3 + 2 or did we want to combine the 3 string with the a 2 string? If we can’t figure out what we want to do, then we certainly can’t expect Ruby to figure it out!

Type Conversions

To solve this error, we need to use a technique called casting or type conversion. Look at this example:

# Casting an integer to a string puts '3' + 2.to_s 

This program displays 32 without throwing an error. By adding .to_s to the integer, we told Ruby “hey, please convert this integer to a string.”

If we wanted to convert a string to an integer instead, we’d use .to_i on the string like this:

# Casting a string to an integer puts '3'.to_i + 2 

This time, the result would be 5 since we would have correctly added the numbers 3 and 2 together.

Whether we converted a string to an integer or the other way around, our program worked because we were explicit.

Let’s nitpick a bit and look at what would happen if we do this:

puts 'hello'.to_i 

Ruby can’t really convert a string like hello to an integer, so it will just output 0 instead. What’s important to note is that it didn’t throw an error.

Try: Try to convert the string 3hello to an integer, see what happens and explain the result. What if you try with hello5 or h3ll0? Play a little bit with these type conversions. If you don’t quite understand what is happening, come ask us in the Forums.

Assigning Operations Results To Variables

Just like how we can assign raw values to variables, we can also assign them the result of an operation. Give it a try:

apples = 3 oranges = 4 fruits = apples + oranges  puts fruits 

This will display 7, and it’s no surprise, right? First we assigned 3 to apples and 4 to oranges. Then we assigned the result of adding them together to fruits (apples + oranges is the same as 3 + 4). Finally, we displayed the text value of the integer contained in fruits, which is 7.

String Interpolation

Mixing Strings And Other Types Together

The previous example only displays 7, which isn’t very descriptive for people using the program: what does this 7 mean? 7 dwarves? No, 7 fruits! So why not display There are 7 fruits instead?

Can you do it? You already know about type casting and string concatenation – you know everything needed to make it happen! See if you can come up with the solution on your own before looking at the solution below.

# A program that displays the number of fruits apples = 3 oranges = 4 fruits = apples + oranges  puts 'There are ' + fruits.to_s + ' fruits' 

That was pretty easy, right? If you solved it on your own, then congratulations! We’re pretty darn proud of you! If you had trouble figuring it out, then don’t worry: just read through the above examples one more time, and maybe ask for help in the Forums.

Double-Quoted Strings

Up until now, we’ve been using single-quoted strings – for example, 'Hello, world!'. We can also use double-quoted strings. If you type puts "Hello, World!", Hello, World! will be displayed in your CLI – same as with single-quotes.

But there is a difference with double-quotes: they’re somewhat of a function! When you use double-quotes, it means “convert anything between these quotes into a string“. To explain the difference, let’s look at an example. Write the following program:

age = 51 puts "You are #{age} years old" 

This program displays You are 51 years old by using a technique called string interpolation, which is a very idiomatic way of writing Ruby code. By wrapping the age variable inside of #{} and within a double-quoted string ("), we were able to insert the value inside of the age value into the string.

We didn’t have to convert age – which held an integer – to a string with .to_s because anything within double quotes is already converted to a string.

You can consider #{} as a placeholder for code inside a string. Anything within this placeholder will be executed before the string is rendered. Let’s look at some more examples:

name = 'Bruce Wayne' age = 34  # Multiple placeholders in a string puts "#{name} is #{age} years old"  # Operation inside a string puts "The result of 3+2 is #{3 + 2}"  # Interpolation doesn't work with single-quotes puts '#{name} is #{age} years old'  # Using single quotes inside a double-quoted string puts "The following word is between single quotes: 'hello'" 

This is what this program outputs:

Bruce Wayne is 34 years old The result of 3+2 is 5 #{name} is #{age} years old The following word is between single quotes: 'hello' 

Let’s take a closer look at each line:

  • In the first line, we used multiple placeholders in the same string. You can. It just works. Thanks, Ruby!
  • In the second line, we didn’t simply put a variable between #{}, we placed an operation. It was properly evaluated. You can do it. It just works too. Thanks again, Ruby!
  • We tried to use string interpolation inside a single-quoted string and it didn’t work. Remember that placeholders do not work in single-quoted strings!
  • Double-quoted strings are also useful if we want to use single quotes in a string.

Special Characters

As we just said, double-quoted strings make it easy to use a single-quote character (') in a string. But what happens if we want to use the double-quote character (") inside of a double-quoted string?

What happens is that Ruby will think that the string has ended when it hasn’t – you’ll probably throw an error. But don’t worry – it’s easy to fix! We just need to put a backslash (\\) in front of the double-quote character. A backslash inside of a string means that the next character is special – in programming, we call it an escape character.

Example: puts "This is a double quote: \" and it gets displayed".

There are a few other special characters you may need in a string, such as tabs (\t), the new line character (\n) or even a backslash (\\):

# The following will be displayed on two lines puts "Hello Dear,\nHow are you?"  # This will insert a tab in the string puts "Quantity:\t42"  # And we display a backslash puts "This character: \\ is a backslash!" 

This is the result:

Hello Dear, How are you? Quantity:       42 This character: \ is a backslash! 

When To Use Double-Quoted Strings

Ruby purists will scream in horror at what we are about to tell you, but here it is: At OptionalBits, we never use single-quoted strings. Nope, never. Even though the whole site is built in Ruby. Always double-quoted strings. Here is why:

The performance (speed of execution) of your programs will be reduced (theoretically) if you use double-quoted strings when single-quoted ones would be enough – when you don’t need string interpolation.

If you use double-quoted strings when single-quoted strings would be enough – for example, when you don’t need to do string interpolation – then the performance (as in speed) of your programs will be theoretically reduced. This is because double-quoted strings are not used “as-is”: they must first be checked by the interpreter to see if any interpolation needs to be done. This means that your processor technically has to do more work than if you had used a single-quoted string – which is why many programmers insist of using single-quoted strings.

But what kind of extra work does this really mean? Well, that’s exactly the question Lawson Kurtz asked. He set forth to measure the impact of double-quoted strings on program performance and published his results.

In his words:

If you’re a pragmatic Ruby programmer, just use double-quoted strings. And if you’re a theoretical performance devotee, well, you’re probably not writing Ruby anyway.

In this day and age, processors (even on the lowest class Android phone) are powerful enough so a user won’t see any difference in an app’s performance between double-quoted strings and single-quoted ones. So you’re not really making your app perform better or provide a better user experience by using single-quoted strings.

And since double-quoted strings make it easier to work with writing strings and using interpolation, we’re going to use them everywhere and be okay with it – purists be damned!

Summary

How are you feeling about yourself as a programmer so far? We’ll bet that you may not feel as though you’re progressing very far – and that’s normal! It may not seem like it, but you are making a lot of progress!

Everything that you have learned forms the base of a programmer’s job. There’s still a long way to go before you can build awesome apps, but you are learning the basics in a structured way that is going to make you a great developer.

Rome wasn’t built in a day, as they say: stay the course, and you’ll be in an exciting new career before you know it!

In this lesson, we learned how Ruby handles operations. Sure, we started off with just addition, but we’ll make use of other operations soon – and they work in the same way. We also learned what casting – also called type conversion – is and why we use it. We introduced double-quoted strings, which are used to perform string interpolations – an idiomatic way for Ruby to concatenate strings and other data types. Finally, we learned how to handle special characters in a string and when you should use single-quoted strings rather than double-quoted strings.

Important Words

  • String concatenation
  • Implicit
  • Explicit
  • Casting
  • Type conversion
  • Double-quoted strings
  • String interpolation
  • Escape character
  • The string interpolation placeholder: #{}
  • \n, \t, \\ and \"

Exercise

You remember the “There are 7 fruits” program we wrote earlier? Try re-writing the program using string interpolation instead of string concatenation. Practice using string interpolation, special characters, casting and operations by experimenting with small programs.

Share your solution and your practice programs in the Forums, because as far as we know, if it’s not in the Forums, you’ve not completed the lesson!

Share to friends