How to Represent "Infinity" in Ruby?

Starting with Ruby v1.9.2, you can represent positive and negative infinity using the Float::INFINITY constant, in the following way:

# Ruby v1.9.2+
Float::INFINITY #=> +infinity
-Float::INFINITY #=> -infinity

In versions of Ruby prior to 1.9.2, you can create your own constants for positive and negative infinity, for example, like so:

# < Ruby v1.9.2
POSITIVE_INFINITY = +1.0/0.0
NEGATIVE_INFINITY = -1.0/0.0

puts POSITIVE_INFINITY #=> +infinity
puts NEGATIVE_INFINITY #=> -infinity

All these representations follow the IEEE 754 floating-point standard and are equivalent to each other. Therefore, you can use them interchangeably in mathematical calculations, comparisons, and other operations.

The value Float::INFINITY or +1.0/0.0 (i.e. positive infinity) is always greater than any other number:

# Ruby v1.9.2+
puts Float::INFINITY > -100 #=> true
puts Float::INFINITY > 0 #=> true
puts Float::INFINITY > 100 #=> true
POSITIVE_INFINITY = +1.0/0.0

puts POSITIVE_INFINITY > -100 #=> true
puts POSITIVE_INFINITY > 0 #=> true
puts POSITIVE_INFINITY > 100 #=> true

Similarly, the value -Float::INFINITY or -1.0/0.0 (i.e. negative infinity) is always less than any other number:

# Ruby v1.9.2+
puts -Float::INFINITY < -100 #=> true
puts -Float::INFINITY < 0 #=> true
puts -Float::INFINITY < 100 #=> true
NEGATIVE_INFINITY = -1.0/0.0

puts NEGATIVE_INFINITY < -100 #=> true
puts NEGATIVE_INFINITY < 0 #=> true
puts NEGATIVE_INFINITY < 100 #=> true

You can check if a value is infinite by using the Float#infinite? method which returns -1 for negative infinity, 1 for positive infinite, and nil otherwise.

For example, you can check if a value is positive infinity in the following way:

def is_pos_inf(value)
  value.infinite? == 1
end

puts is_pos_inf(Float::INFINITY) #=> true
puts is_pos_inf(+1.0/0.0) #=> true

puts is_pos_inf(-Float::INFINITY) #=> false
puts is_pos_inf(-1.0/0.0) #=> false

puts is_pos_inf(42) #=> false
puts is_pos_inf(-42) #=> false

Similarly, you can check if a value is negative infinity in the following way:

def is_neg_inf(value)
  value.infinite? == -1
end

puts is_neg_inf(-Float::INFINITY) #=> true
puts is_neg_inf(-1.0/0.0) #=> true

puts is_neg_inf(Float::INFINITY) #=> false
puts is_neg_inf(+1.0/0.0) #=> false

puts is_neg_inf(42) #=> false
puts is_neg_inf(-42) #=> false

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.