๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

Ruby Math

A math method is a built-in tool that works on a number. Some tools change a number slightly and one tool finds a square root.

Dropping the sign

The abs method drops the sign from a number. It prints the size of the stored value.

value = -9
puts value.abs

Round, floor and ceil

round moves a float to the nearest whole number. floor moves it down and ceil moves it up.

puts 4.6.round
puts 4.6.floor
puts 4.2.ceil

One float, three moves

The same float can move in three ways. Each method prints a whole number.

puts 4.4.round
puts 4.4.floor
puts 4.4.ceil

Square root

Math.sqrt finds the square root of a number. The answer prints as a float.

puts Math.sqrt(16)

Example

puts 7.8.floor
puts 7.1.ceil
puts 7.5.round
puts Math.sqrt(25)

Key points

  • Use abs to get the size of a number without its sign.
  • Use round to move a float to the nearest whole number.
  • Use floor to move a float down to a whole number.
  • Use ceil to move a float up to a whole number.
  • Use Math.sqrt to find the square root of a number.

In this example, floor moves 7.8 down and prints 7. ceil moves 7.1 up and prints 8. round moves 7.5 to the nearest whole number and prints 8. Math.sqrt finds the square root of 25 and prints 5.0.

Note

Math.sqrt gives a float, so Math.sqrt(16) prints 4.0 and not 4.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does puts Math.sqrt(9) print?