Nithin Bekal

# Infinity in Ruby

03 Mar 2015

Have you ever wondered how Ruby handles infinity? We’ve all run into the divide-by-zero error when diving an integer by zero, but things are different in case of floating point numbers.

As you can see above, Ruby gives you a value that represents infinity when a floating point operation returns an infinite value.

There isn’t a constant with the name `Infinity`, as shown by the NameError that we encountered when trying to access it directly. But it is available as the constant `Float::INFINITY`. Let’s take a closer look at it.

Ok, now that we know that it’s a value of type Float, let’s try some arithmetic operations on it.

# `NaN` - not a number

Subtraction and division of two infinite values yield undefined results. Now we have another kind of value, `NaN`, to represent such values. Let’s dig into `NaN` for a minute.

# Infinite ranges

One interesting use of `Infinity` is to get infinite ranges.

You need to be careful when using methods like `#select` because you might end up with an infinite loop while `#select` keeps checking every number because it never reaches `Infinity`.

In such cases, you can use the `Enumerable#lazy` method to create a lazy enumerator and then use the `#first` method to take a certain number of items from that list.

# An example

Let’s look at an situation where we might find infinite ranges useful. You have an `Article` class, and need to implement a `within_word_limit?` method that checks if the word count is between `@min_word_count` and `@max_word_count`.

If either of those variables is nil, that limit does not exist, ie. the range would be `0..Infinity`. Here’s one way of doing it by setting the upper limit of the range as infinity.

We could do this by using the comparison operators and if statements, but using a range makes it much more readable. 