How to Store Strings in Ruby Variables - dummies

How to Store Strings in Ruby Variables

By Christopher Haupt

Ruby lets you store any data type in a variable, and strings are no exception to that. Here’s how to store your name in a variable:

2.2.2 :016 > name = "Chris"
=> "Chris"

To confirm it’s in there, do the following:

2.2.2 :017 >name
=>"Chris"

Create another variable for a greeting:

2.2.2 :018 > greeting = "Howdy there!"
=> "Howdy there!"

Now use string addition to assemble a full welcome message:

2.2.2 :019 > greeting + " " + name
=> "Howdy there! Chris"

See how you actually added three things together? You used the greeting variable, plus a string with a space in it, plus the name variable. You can string together as many strings as you want this way.

Try changing the order or adding together other words. You can also combine techniques to get more interesting results:

2.2.2 :024 > greeting = "hi "
=> "hi "
2.2.2 :025 > (greeting * 5) + name
=> "hi hi hi hi hi Chris"