What is the magnitude() method of a float in Ruby?

Overview

The magnitude() method of a float is used to convert a float value to its absolute form.

Syntax

float_value.magnitude()

Parameters

This methodis only invoked on the float value.

Return value

This method returns the absolute value of the float_value.

Code

# create some float values
f1 = 2.222
f2 = 3.4/-0.222
f3 = -(3 + 3) * 2
f4 = 20.92
# print magnitudes
puts f1.magnitude
puts f2.magnitude
puts f3.magnitude
puts f4.magnitude

Code explanation

  • Lines 2–5: We create four variables f1, f2, f3, and f4 that contain different float values.

  • Lines 8–11: We invoke the magnitude() method on these float values and print the returned results to the console, using the puts method.

Free Resources