Is there a keyword to express Infinity in Ruby?
Asked
Active
Viewed 6.5k times
3 Answers
213
If you use ruby 1.9.2, you can use:
>> Float::INFINITY #=> Infinity
>> 3 < Float::INFINITY #=> true
Or you can create your own constant using the following*:
I've checked that in Ruby 1.8.6, 1.8.7, and 1.9.2 you have Float.infinite?.
PositiveInfinity = +1.0/0.0
=> Infinity
NegativeInfinity = -1.0/0.0
=> -Infinity
CompleteInfinity = NegativeInfinity..PositiveInfinity
=> -Infinity..Infinity
*I've verified this in Ruby 1.8.6 and 1.9.2
-
2Right. I tried doing comparisons between any integer and that value and it seems to be working fine. I am just wondering now if this is safe! – Amokrane Chentir Apr 25 '11 at 12:38
-
1There's a nice article here describing the properties of Infinity in Ruby (including Infinity derived via dividing by 0): http://nithinbekal.com/posts/ruby-infinity/ - should give you an idea whether or not it's safe. (For what it's worth, IMHO messing around with numeric Infinity values is virtually never safe or truly needed regardless of what programming language you're using, unless you're doing actual math-related work) – Andrew Faulkner Jan 02 '16 at 10:54
-
This is great, thanks, I believe you can also do `-Float::INFINITY` for negative infinity. – Saleh Rastani Feb 12 '19 at 03:43
103
No keyword, but 1.9.2 has a constant for this:
>> Float::INFINITY #=> Infinity
>> 3 < Float::INFINITY #=> true

Michael Kohl
- 66,324
- 14
- 138
- 158
-
+1, I didn't realize this was in 1.9.2. I've updated my answer directing people to your answer if that is the version they are targeting. – Matt Apr 25 '11 at 13:04
8
Consider BigDecimal in the ruby docs
1.9.3p429 :025 > BigDecimal('Infinity')
=> #<BigDecimal:7f8a6c548140,'Infinity',9(9)>
1.9.3p429 :026 > BigDecimal('-Infinity')
=> #<BigDecimal:7f8a6a0e3728,'-Infinity',9(9)>
1.9.3p429 :027 > 3 < BigDecimal('Infinity')
=> true
1.9.3p429 :028 > BigDecimal::INFINITY
=> #<BigDecimal:7f8a6ad046d8,'Infinity',9(9)>

i_want_more_edits
- 131
- 6

davidtingsu
- 1,090
- 1
- 10
- 17