Ruby abs() Method

Ruby abs() Function with Examples

Ruby abs() method is an integer class function that is used to find the absolute value of an integer number. Applying this method to any other data type raises an error.

Ruby abs() Method

Syntaxnum.abs()
Where num is the integer value which should be absolute.
ParametersThis method does not accept any parameter.
Return valueReturn the absolute value of a given integer.

Example Program-1:

# use directly
num1 = -22
num2 = -100
num3 = 2
num4 = 0

puts num1.abs
puts num2.abs()
puts num3.abs
puts num4.abs()
puts -45.abs

Output

22
100
2
0
45

Example Program-2:

# non-absoluute values
a = 20
b = -12
c = 0

# converting to absolute value
x = a.abs
y = b.abs
z = c.abs()

puts x
puts y
puts z

Output

20
12
0
Posted in