gpt4 book ai didi

ruby - 在 Ruby 中什么可以强制转换为整数?

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

在 Ruby 中,如果你尝试做 2 + nil ,例如,你得到

TypeError: nil can't be coerced into Integer

但是,这让我想知道是否有任何东西可以强制转换为 Integer .很多次Integer s 被强制转换为其他数字类型,如下所示

(2 + Rational('1/2')).class 
# => Rational
(2 + 0.5).class
# => Float
(2 + 1i).class
# => Complex

并且,Ruby 中的 bool 值不会被强制转换为 Integer .那么,什么会被强制转换为 Integer? ?

最佳答案

在 ruby​​ 中,任意类都可以通过定义 coerce 方法来选择对其他类型进行强制转换。这个有详细介绍here .

关于ruby - 在 Ruby 中什么可以强制转换为整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41914409/

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