Numbers
Prerequisites: Data types
Ruby has two main number types: Integer for whole numbers and Float
for numbers with a decimal point.
Syntax
count = 42
price = 9.99
population = 8_100_000_000 # underscores are just for readability
Integers have no size limit — Ruby grows them as needed, so
2 ** 100 just works.
Example
puts 7 + 2
puts 7 - 2
puts 7 * 2
puts 7 / 2
puts 7 % 2
puts 7 ** 2
puts 7 / 2.0
puts 7.fdiv(2)
puts 10.0 / 3
puts (10.0 / 3).round(2)
Expected output
9
5
14
3
1
49
3.5
3.5
3.3333333333333335
3.33
Line by line:
7 / 2is3, not3.5. When both numbers are integers,/does integer division and drops the remainder.%(modulo) gives the remainder:7 % 2is1. It's handy for checking whether a number is even.**raises to a power.- If either side is a
Float, the result is aFloat.fdivalways returns aFloat. - Floats are approximate:
10.0 / 3shows the tiny rounding error built into how computers store decimals. Useround(2)for display.
Numbers are objects with useful methods:
p -5.abs
p 10.even?
p 3.7.floor
p 3.2.ceil
p 17.clamp(1, 10)
5
true
3
4
10
Common mistakes
- Expecting
7 / 2to be3.5. Make one side a float (7 / 2.0) or usefdiv. - Using
Floatfor money.0.1 + 0.2is0.30000000000000004. For money, store whole cents as integers (1999for $19.99), or use theBigDecimallibrary.
Practice
A pizza has 8 slices shared by 3 people. Print how many whole slices each person gets, and how many are left over.
Show solution
slices = 8
people = 3
puts slices / people
puts slices % people
2
2