How to know if a float value is infinite in Ruby

Overview

An infinite number is a number that has no end and is not measurable. We can have infinite numbers that are positive and negative. These numbers are called positive infinity and negative infinity. We can check if a float value is infinite or not by using the infinite? method.

Syntax

fl_num.infinite?

Parameters

This method takes no parameters. They are only invoked on a float object or value.

Return value

The value returned is 1, -1, or nil. 1 is returned if it is infinity or positive infinity. -1 is returned if it is negative infinity. Otherwise, nil is returned.

Code example

# create float values
f1 = 2.3435
f2 = 1.0/0.0 # infinity
f3 = -3.4/0.0 # -infinity
f4 = 4.34/1.2
# check if infinity
puts "#{f1} is : #{f1.infinite?}"
puts "#{f1} is : #{f2.infinite?}"
puts "#{f1} is : #{f3.infinite?}"
puts "#{f1} is : #{f4.infinite?}"

Explanation

  • Lines 2 to 5: We create some float variables and initialize them with some values.
  • Lines 8 to 11: We use the infinite? method to determine whether the float values are infinite or not. We then print the results on the console.
New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources