Strings

Goals

Step 1

A string is a series of characters. Strings can be created using either single or double quotes.

These strings weren't saved into a variable. What happens to data not saved into a variable?

What happens if you start a string with one kind of quote and end with another? How can you fix it?

Step 2

Type this in irb:

'Hello, ' + 'Jane'
'apples' * 3

Strings can be added to each other or multipled by numbers. What does this do?

Step 3

Type this in irb:

name = 'Jane'
"Hello #{name}"

(the {} characters are generally called curly braces)

This is called string interpolation. String interpolation lets you embed a Ruby statement in another string. It only works with double quotes: what happens when you try the same thing with single quotes?

Type this in irb:

"Two plus two is #{2 + 2}"

The code in the curly braces can be any valid Ruby statement. Try putting various things in the curly brackets to see what works and what doesn't.

Step 4

Recall that you can see what methods
are available for an object by calling .methods on it.

Type this in irb:

'some string'.methods

Explanation

Strings are a key way to present information in your programs. Since a human will probably be reading the output of your program eventually, and humans speak words rather than numbers, you will often want to use strings.