Strings

The word we use for groups of characters is string. Here are some strings:

  • “Hello.”
  • “Ruby rocks.”
  • “5 is my favorite number… what’s yours?”
  • “Rainbows are difficult to touch.”

Some things you can do with strings

Ruby lets you do several nifty things with strings.

shell> irb --simple-prompt
>> "Hello " + "World"
=> "Hello World"
>> "hi " * 3
=> "hi hi hi "

Here is a good way to remember this: "hi " * 3 is the same as "hi " + "hi " + "hi " so it gives me "hi hi hi ".

Notice what happens if I forget the space in "hi ":

>> "hi" * 3
=> "hihihi"

Now see what happens here:

>> "1" + "2"
=> "12"
>> "1" * 2
=> "11"

When Ruby sees “1” it sees a string, not a number.

More things you can do with text

Here are some more nifty things you can do with text:

>> "ninja".capitalize
=> "Ninja"
>> "ninja".reverse
=> "ajnin"
>> "ninja".upcase
=> "NINJA"
>> "NINJA".downcase
=> ninja

Further reading

Ruby String Class Manual

First Steps, Strings, New names for old things