Variables in Ruby
A variable is a named memory location where we can keep values for a specific program. In simpler terms, a variable is a name used to store a value.
A variable is also called an identifier and is used to store a value. In Ruby, variables are created when values are assigned to them.
Syntax:variable_name = value
Example
# Creating variables
sname = "Madhu"
age = 20
cgpa = 7.5
# Print variables
puts sname
puts age
puts cgpa
Output:
ruby variables.rb
Madhu
20
7.5
In the above example, sname, age and cgpa are variables, while "Madhu", 20 and 7.5 are values.
Ruby is a dynamically typed language. Therefore, we do not need to declare the data type of a variable explicitly.
Rules for Naming Variables in Ruby
In Ruby, a variable can be given a simple name, such as a or b, or it can have a more detailed name like first_name, age, or fullname.
There are some rules for naming variables in Ruby:
- Variable names can contain letters, numbers and underscores.
- A variable name should begin with a lowercase letter or underscore.
- Variable names cannot begin with a number.
- Ruby variable names are case-sensitive.
- Reserved keywords cannot be used as variable names.
- Spaces are not allowed in variable names.
Examples
Valid variable names:name = "Madhu"
student_age = 20
_count = 10
num1 = 45
Invalid variable names:
2name = "Madhu" # Starts with a number
student age = 20 # Contains a space
@name = "Madhu" # Starts with a special character
Constants in Ruby
A constant is a name used to store a value that is intended to remain unchanged throughout the program. These are used for fixed or configuration values.
Syntax:CONSTANT_NAME = value
Example
# constant
PI = 3.14159
puts PI
Output:
3.14159
Note: Constants are generally written using uppercase letters.