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 = valueFor 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 integer2. 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 1The decimal point is what distinguishes a float from an integer - even 5.0 is a float, not an integer.
Challenge
EasyCreate 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 = valueIntegers are whole numbers without decimal points:
count = 100 # Positive integer
temperature = -5 # Negative integer
zero_value = 0 # ZeroFloats are numbers with decimal points:
price = 19.99 # Positive float
temperature = -3.5 # Negative float
percentage = 0.75 # Float between 0 and 1To display variables, use puts:
age = 25
puts ageTry it yourself
# TODO: Create the variables below
# Don't delete the rows below
puts student_count
puts average_scoreThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 42Variables and Data Types
Numbers and VariablesString Data TypeBoolean Data TypeSymbol Data TypeChecking Data TypesNaming ConventionsRecap - Variable Creation8Loops
For Loop with RangesWhile LoopBreakNextRecap - FactorialTimes LoopUntil LoopNested LoopsRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators6Basic IO
Output with putsOutput with print and pOutput With VariablesInput with getsChomp MethodType ConversionRecap - Age CalculatorRecap - True or False