Ruby PlaygroundRuby Tutorial
UI ThemeDark

Lesson 3 of 23 · Ruby 3.4

Calculate with numbers

Use integer and floating-point arithmetic to calculate quantities.

Learn

Whole numbers such as 18 are Integers. Numbers written with a decimal point, such as 18.0, are Floats. Use + to add, - to subtract, * to multiply and / to divide. These operations produce values you can assign or display.

Multiplication and division have higher precedence than addition and subtraction. Parentheses group a calculation that should happen first. Dividing two Integers produces an Integer quotient rounded down; a Float operand requests floating-point division instead.

Example

price = 6
quantity = 3
p price * quantity
p 18 / 4
p 18.0 / 4

Experiment

  • This calculation charges delivery for each item. Edit it so the delivery cost is added once after calculating the item total.

  • Run to inspect the whole-number quotient. Change only 11 to 11.0 to calculate a share that can include a fractional part.

Explore the official manual

Ruby 3.4.1 · Example

Ready to run

Output

Run the code to see what happens.