【发布时间】:2021-12-03 10:57:03
【问题描述】:
假设我创建了一个对象 a 并给它一个方法 .to_i,为什么不能将这个对象添加到 Integer 中?
>> a = Object.new
=> #<Object:0x0000000006cfa9d0>
?> def a.to_int
?> 42
>> end
=> :to_int
>> 3 + a
(irb):5:in `+': Object can't be coerced into Integer (TypeError)
from (irb):5:in `<main>'
感谢 Stefan,它成功了!
irb(main):010:1* def a.coerce other
irb(main):011:1* [other, 42]
irb(main):012:0> end
=> :coerce
irb(main):013:0> 1 + a
=> 43
【问题讨论】:
-
看起来您正在寻找
coerce方法:stackoverflow.com/questions/2799571/… 但是这仅适用于3 + a,对于a + 3,您需要覆盖+方法。
标签: ruby type-conversion integer