Variables

Assignment

A variable stores a value under a name so you can reuse it later. The single equals sign copies the value on the right into the name on the left.

name = "Ada" age = 36 puts name # prints Ada puts age # prints 36

Variables hold any object, and you may store a new value in the same name at any time. Ruby never asks you to declare a type first.

Naming rules snake_case

Local variable names start with a lowercase letter or an underscore, then use lowercase letters, digits, and underscores. Words are joined with underscores, a style called snake_case.

Names cannot start with a digit and cannot contain spaces or dashes. A leading capital letter would turn the name into a constant, which is the topic of the last section.

first_name = "Ada" score_2 = 10 puts first_name # prints Ada

Parallel assignment

Ruby can fill several variables in one line when the counts on both sides match. The first value goes into the first name, the second into the second name, and so on.

x, y = 1, 2 puts x # prints 1 puts y # prints 2

The classic trick is a swap with no helper variable. The right side builds a pair first, then Ruby unpacks it into the two names:

x, y = y, x puts x # prints 2 puts y # prints 1

Constants shout

A constant holds a value that should stay fixed, such as a limit or a title. Constants start with a capital letter, and multi-word constants use all caps with underscores.

LIMIT = 10 APP_NAME = "Demo" puts LIMIT # prints 10

Ruby only warns when you reassign a constant instead of stopping you, so treat the warning as an error in your own code and pick a new name when a value must change.

Next: Numbers

Article author: Arthur Isaev