Ruby’s variables are dynamic, meaning you don’t need to declare their type explicitly. This is similar to JavaScript, and Python, but vastly different from C/C++, Java, TypeScript, and Go.
Types of Variables
Ruby is a little different in how it handles different types of variables, defining them by different prefixes.
Local Variables
- Start with a lower case letter, or an underscore.
- Scope is limited to the block or method where they are defined.
name = "Alice"
age = 30
Notice how Ruby identifies the data type based upon how it is used. Variables can be redefined, not only in their value, but also the type of data they hold during runtime, similar to Python.
name = "Alice"
puts name # prints Alice
name = 89 # prints changes value and type of variable
puts name # prints 89
Notice how for a single line comment, it starts with a #
. This is similar to some other languages like SQL, and PHP.
Constants
- Start with an uppercase letter.
- Their values should not change (though they can be modified with a warning).
PI = 3.14
Global Variables
- Accessible from anywhere in the program but should be avoided for clarity and maintainability.
- Start with
$
.
$num_of_items = 15
Instance Variables
- These are properties of a class… or an object’s instance if you would.
- They are available to any method within an object.
- They start with an
@
.
@name = "Alice"
Class Variables
- Begin with
@@
. – Notice how it is similar to the Instance Variables. - Shared across all instances of a class.
@@count = 0
Understanding Variables in Ruby was originally found on Access 2 Learn