Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 2 of 23 · Ruby 3.2

Name and reuse values

Assign values to local variables and reuse those names in a program.

Learn

An assignment gives a value a name: destination = "Harbor" assigns the string to the local variable destination. Write the name later to use its current value. The = sign performs assignment.

Choose lowercase names that describe the value, such as destination or departure_time. Use underscores to separate words. Assign a variable before reading it. A later assignment to the same name replaces the value that name will provide.

Example

destination = "Harbor"
puts destination
puts destination
destination = "Museum"
puts destination

Experiment

  • Change the message assignment to a different announcement. Before running, predict which displayed lines will use your new text.

  • Predict the two values before running. Change the final assignment to seats and check whether reserved also changes.

Explore the official manual

Ruby 3.2.4 · Example

Ready to run

Output

Run the code to see what happens.