Variables
6 min · Ruby
Store values in named boxes called variables.
Enemy 1 of 5
Creating a variable
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.
Loading editor...