Variables in Ruby
In this tutorial, we will learn about variables in Ruby. We will cover the basics of declaring and using variables, including naming conventions.
What are Variables
Variables in Ruby are used to store data values that can be manipulated during program execution. Ruby is a dynamically typed language, meaning the data type of a variable can change at runtime.
Syntax
The syntax to declare variables in Ruby is:
variable_name = value
Rules for Naming Variables
When naming variables in Ruby, follow these conventions:
- Variable names must start with a lowercase letter or an underscore (_).
- Subsequent characters can include letters, digits, and underscores.
- Variable names are case-sensitive.
- Avoid using reserved keywords as variable names.
- Use snake_case naming convention for readability.
Example 1: Variable storing Integer Value
In Ruby, we can store an integer value in a variable.
For example,
- Declare a variable named
num
. - Assign a value of 10 to the variable using assignment operator
=
. - Print the value of the variable using puts method.
Ruby Program
# Declare and initialize an integer variable
num = 10
# Print the value of the variable
puts "The value of num is: #{num}"
Output
The value of num is: 10
Example 2: Variable storing String Value
In Ruby, we can store a string value in a variable.
For example,
- Declare a variable named
name
. - Assign the string value 'Arjun' to the variable using assignment operator
=
. - Print the value of the variable using puts method.
Ruby Program
# Declare and initialize a string variable
name = 'Arjun'
# Print the value of the variable
puts "The value of name is: #{name}"
Output
The value of name is: Arjun
Example 3: Variable storing Boolean Value
In Ruby, we can store a boolean value in a variable.
For example,
- Declare a variable named
is_true
. - Assign the boolean value
true
to the variable. - Print the value of the variable using puts method.
Ruby Program
# Declare and initialize a boolean variable
is_true = true
# Print the value of the variable
puts "The value of is_true is: #{is_true}"
Output
The value of is_true is: true