All lessons

Variables

6 min · Ruby

Store values in named boxes called variables.

Ruby · Variables0/5 cleared

Enemy 1 of 5

Creating a variable

This code stores the text Ada in a variable called name, then uses puts to print it. No keyword is needed to make a variable in Ruby. Press Run to see Ada.

Why this works

A variable is a named container that holds a value so you can refer back to it later instead of retyping it every time. In Ruby, you create one simply by writing name = value: no keyword like var or let, and no special sigil like PHP's $, is required. This is part of Ruby's design philosophy of removing anything that doesn't need to be there.

Because there's no keyword, the very act of writing word = value is what tells Ruby "this is a new local variable" (assuming word hasn't been used as one already). That's different from languages that require you to declare a variable's existence separately from giving it a value. In Ruby, assignment and declaration are the same act.

Ruby is dynamically typed, meaning you never declare what type of value a variable will hold. A variable can hold a string today and a number tomorrow if you reassign it. The type lives with the value, not with the variable name.

Once a variable holds a value, you use it just by writing its bare name anywhere you'd use the value itself: puts name prints whatever's currently stored in name.

You
Cold-Start Frostling
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.