Ruby magnitude Method

Ruby magnitude Function with Examples

Ruby magnitude method is an integer class function that is used to find the absolute value of a specified integer. This function is the same as the Ruby abs() method.

This method also supports the double data type, which means you can find the absolute value of a negative double value (ex: 23.22). Assigning other data types will through an error.

Ruby magnitude Method

Syntaxnum.magnitude or num.magnitude()
Where num is the integer or double number to find the absolute value.
ParametersThis method does not accept any parameters. It directly takes the integer number as an object.
Return valueReturns the absolute value of the specified integer or double number.

Example Program-1:

num1 = -23
num2 = -10
num3 = 30

x = num1.magnitude
y = num2.magnitude()
z = num3.magnitude

puts x
puts y
puts z

Output

23
10
30

Example Program-2:

num1 = 22
num2 = -12
num3 = -30
num4 = 0
num5 = -45.50

puts num1.magnitude
puts num2.magnitude
puts num3.magnitude
puts num4.magnitude()
puts num5.magnitude
puts -17.magnitude

Output

22
12
30
0
45.5
17
Posted in