What is infinity in Ruby?
It’s something that has a starting point but no ending.
In Ruby, we can express this concept of infinity with the
You may be wondering how this is useful.
Let me explain with examples!
Ruby returns an
Infinity object, as the result of certain math operations.
You may be familiar with the “division by zero” error.
Here it is:
1/0 # ZeroDivisionError: divided by 0
If you use a float, you get something else:
1/0.0 # Infinity
But that’s not all.
If you try a division of
0.0, then you get another special value.
Take a look:
0/0.0 # NaN
What is this NaN?
It means “Not a Number”, and as far as I know, this is the only place in Ruby where you’ll find this value.
Why is this a thing?
It’s part of the IEEE 754 Specification, which explains how floating-point operations should behave.
Btw, there are some related methods:
You can use these methods to check for special values.
These methods are available on Floats.
Since Ruby 2.4 you can also use
infinite? with Integers.
That was interesting… let’s see more examples.
Now with Ranges!
Here’s an infinite range:
(1..Float::INFINITY).take(10) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
This can be helpful when you don’t know the end of the range in advance.
It only works with numbers as the starting value.
("a"..Float::INFINITY) # ArgumentError: bad value for range
What’s the solution?
With Ruby 2.6, you can do this:
("a"..).take(5) # ["a", "b", "c", "d", "e"]
Yes, that’s not a mistake! This range has no ending value, only a starting value of
"a", then two dots
.. to make it a never-ending range.
This is new syntax.
Use Ruby 2.6+ if you want this to work.
Another practical use for
It’s the biggest (
Infinity) & smallest (
-Infinity) number in Ruby.
You can use this as a starting value.
Here’s an example:
def smallest_percent_size(style, ary_size) @smallest_percent ||= Float::INFINITY if style == :percent && ary_size < @smallest_percent @smallest_percent = ary_size end @smallest_percent end
This code is from Rubocop, an open-source project.
Here's how it works:
We are trying to find the smallest array size, but we need a starting value for that because using
nil would give you an error.
You could type a big number & hope that's enough.
Or you can use
Float::INFINITY, knowing that's that biggest number possible.
You have learned about infinity in Ruby, what it is, where it may show up & how to use it.
Please share this article so more people can benefit from it.
Thanks for reading!