How to Use Variables and Constants in Ruby

09/18/2021

Contents

In this article, you will learn how to use variables and constants in Ruby.

How to use variables and constants

In Ruby, variables are used to store values or data that can be changed, while constants are used to store values that cannot be changed during program execution. Here’s how you can use variables and constants in Ruby:

Creating variables

To create a variable in Ruby, you need to give it a name and assign a value to it using the assignment operator =. Here’s an example:

age = 25
name = "John"

In this example, age and name are variables, and 25 and “John” are their respective values.

Using variables

You can use variables in Ruby to perform calculations, concatenate strings, and more. Here are some examples:

# Using variables to perform calculations
num1 = 10
num2 = 20
sum = num1 + num2
puts "The sum is #{sum}"

# Using variables to concatenate strings
first_name = "John"
last_name = "Doe"
full_name = "#{first_name} #{last_name}"
puts "My name is #{full_name}"

Creating constants

To create a constant in Ruby, you need to use uppercase letters for the variable name, and assign a value to it using the = operator. Here’s an example:

PI = 3.14159

In this example, PI is a constant, and 3.14159 is its value.

Using constants

You can use constants in Ruby just like variables, but you cannot change their value during program execution. Here’s an example:

# Using a constant to perform a calculation
radius = 5
area = PI * radius ** 2
puts "The area of the circle is #{area}"

In this example, PI is a constant, and it is used to calculate the area of a circle. Note that we cannot change the value of PI during program execution.