문제

I can get Infinity and NaN by

n = 9.0 / 0 #=> Infinity
n.class #=> Float

m = 0 / 0.0 #=> NaN
m.class #=> Float

but when I want to access Infinity or NaN directly:

Infinity #=> uninitialized constant Infinity (NameError)
NaN #=> uninitialized constant NaN (NameError)

What are Infinity and NaN? Are they objects, keywords, or something else?

도움이 되었습니까?

해결책

What you see printed as Infinity and NaN are just the string representations for two special instances of the Float class, not keywords or literals. They are returned by floating point division by 0 or by referencing the constants Float::INFINITY and Float::NAN.

Float::INFINITY.class
# => Float
Float::INFINITY.to_s
# => "Infinity"

Float::NAN.class
# => Float
Float::NAN.to_s
# => "NaN"

다른 팁

If you want inf/nan literal, use follow:

>> Float::INFINITY
=> Infinity
>> Float::NAN
=> NaN

See Float constants list

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top