Menu
Coddy logo textTech

Numbers and Variables

Part of the Fundamentals section of Coddy's Ruby journey — lesson 4 of 88.

Variables are containers that hold data values. They are used to store, manipulate, and display information within a program.

In short, a variable is like a memory unit that we can access by typing the name of the variable. Each variable has a unique name and a value that can be of different types. Ruby is capable of automatically detecting the variable type, which makes coding more efficient.

To initialize a variable in Ruby, we use the following format:

variable_name = value

For example:

age = 25
name = "Alice"

Numeric Data Types

Ruby has two main numeric data types for working with numbers:

1. Integers - whole numbers without decimal points. They can be positive, negative, or zero:

count = 100       # Positive integer
temperature = -5  # Negative integer
zero_value = 0    # Zero is also an integer

2. Floats - numbers that contain decimal points. They are used to represent fractional values:

price = 19.99      # Positive float
temperature = -3.5 # Negative float
percentage = 0.75  # Float between 0 and 1

The decimal point is what distinguishes a float from an integer - even 5.0 is a float, not an integer.

challenge icon

Challenge

Easy

Create two numeric variables to represent classroom data. First, create a variable called student_count and assign it the integer value 30. Then create a variable called average_score and assign it the float value 87.5. Finally, display both variables using the puts command.

Cheat sheet

Variables are containers that store data values. To create a variable in Ruby:

variable_name = value

Integers are whole numbers without decimal points:

count = 100       # Positive integer
temperature = -5  # Negative integer
zero_value = 0    # Zero

Floats are numbers with decimal points:

price = 19.99      # Positive float
temperature = -3.5 # Negative float
percentage = 0.75  # Float between 0 and 1

To display variables, use puts:

age = 25
puts age

Try it yourself

# TODO: Create the variables below


# Don't delete the rows below
puts student_count
puts average_score
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals