Ruby data: numbers & booleans
This course covers how Ruby handles numbers and booleans. It starts with the difference between Integer and Float, how the two mix in arithmetic, and how to convert between them. It then explains integer division and the % operator, why 0.1 + 0.2 gives 0.30000000000000004, and how to store money as integer cents or BigDecimal. Later lessons cover numeric methods such as round, abs and even?, the values true and false, and Ruby's truthiness rule. A final challenge combines these ideas in an average method.
What you'll learn
- ✓Telling Integer from Float and converting with to_f and to_i
- ✓How integer division and the % operator behave
- ✓Why floats are imprecise and how to compare or store them safely
- ✓Using round, ceil, floor, abs, even?, odd? and zero?
- ✓Booleans as objects produced by comparison operators
- ✓Ruby's truthiness rule, where only false and nil are falsy
Integer and float: two kinds of number
5 and 5.0 are the same value in math. In Ruby they're different kinds of object.
Read the full lesson free →Curriculum
7 lessonsInteger and float: two kinds of number
Introduces Integer and Float, shows that mixed arithmetic returns a Float, and how to_f and to_i convert values.
Integer division: the classic gotcha
Shows why dividing two Integers drops the fraction, how to get a fractional result, and what % returns.
Float precision: why 0.1 + 0.2 isn't quite 0.3
Explains why 0.1 + 0.2 differs from 0.3 and how to compare floats and store money safely.
Numeric methods: useful built-ins
Covers round, ceil, floor, abs, even?, odd? and zero? as named tools for everyday numeric questions.
Boolean values: true, false, and nothing else
Presents true and false as objects of TrueClass and FalseClass, produced mostly by comparison operators.
Truthiness: what counts as "true enough"
Explains that every Ruby value is truthy except false and nil, including 0, empty strings and empty arrays.
Putting it together: a small challenge
Combines conversion, division and comparison in an average method and a passing? method that returns a boolean.