gpt4 book ai didi

ruby - 为什么 `1i.to_i` 引发 `RangeError` 而不是 `NoMethodError` ?

转载 作者:数据小太阳 更新时间:2023-10-29 07:21:55 26 4
gpt4 key购买 nike

NoMethoErrorto_i 引发,仅仅是因为该类没有方法:

[].to_i # >> NoMethodError (undefined method `to_i' for []:Array)

果然,1i 有方法to_ito_f,所以它响应它们。但实际上这看起来非常棘手。

1i.respond_to?(:to_i) # => true
1i.to_i # >> RangeError (can't convert 0+1i into Integer)

Range 类从哪里来?

最佳答案

Surely enough, 1i has the method .to_i and .to_f so it responds to them. But in reality this looks very tricky!

是的,它会回应他们。当您在复杂文字 1i 上调用 to_i 时,该方法会抛出 RangeError。这与 Range 类无关;它告诉你,虽然 1iComplex 类的 to_i 方法,但它的具体值不是一个可以得到有意义结果的值.

或者换句话说,这就是Complex::to_i 在虚部非零甚至不精确的对象上调用时:

to_i → integer

Returns the value as an integer if possible (the imaginary part should be exactly zero).

Complex(1, 0).to_i    #=> 1
Complex(1, 0.0).to_i # RangeError
Complex(1, 2).to_i # RangeError

RangeError 粗略地表示一个参数超出了它所提供的函数的范围,即数学意义上的“范围”。 Complex 在将这种“范围”感应用于目标对象时有点不寻常,这与方法参数相反,但它仍然有意义。

关于ruby - 为什么 `1i.to_i` 引发 `RangeError` 而不是 `NoMethodError` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54809108/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com