How to Find the Absolute Value of a Number in Ruby?

In Ruby, you can get the absolute value of a number by using the Numeric#abs method (or its alias, Numeric#magnitude), for example, like so:

puts 1234.abs #=> 1234
puts (-12.34).abs #=> 12.34
puts -12.34.abs #=> 12.34

Since the Numeric#magnitude method is an alias of Numeric#abs, it would yield the same result:

puts 1234.magnitude #=> 1234
puts (-12.34).magnitude #=> 12.34
puts -12.34.magnitude #=> 12.34

However, please note that the following case, where the numeric value is in parentheses and the minus sign is outside:

puts -(1234).abs #=> -1234

In this case, the resulting value keeps the minus sign. This is because the absolute value is calculated only for the numeric value in parentheses and then the minus sign is added.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.