All lessons

Numbers & Math

6 min · Ruby

Do math with variables and the basic operators.

Ruby · Numbers & Math0/5 cleared

Enemy 1 of 5

Arithmetic in Ruby

Ruby supports the standard arithmetic operators: + (add), - (subtract), * (multiply), and / (divide), and you can use them on numeric literals directly or on variables that hold numbers. Ruby follows the usual mathematical order of operations, so multiplication and division are evaluated before addition and subtraction unless you use parentheses to change that order.

Ruby has two main kinds of numbers: Integer for whole numbers and Float for decimals. Dividing two integers with / performs integer division and truncates any remainder (7 / 2 is 3, not 3.5) — a classic gotcha if you're expecting a precise decimal result. If you need a fractional answer, make at least one side a float (7.0 / 2 gives 3.5).

In the example, puts price * quantity is evaluated in one step: Ruby computes price * quantity first (following order of operations), and only then does puts print the resulting number.

You
Syntax Skeleton

Loading editor...

Ln 1, Col 1Spaces: 4
Sign up to fightTarget output: 15