假設我創建了一個物件 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
uj5u.com熱心網友回復:
可以通過實作來實作向物件添加整數 ,例如:
class Foo
def initialize(value)
@value = value
end
def to_i
@value
end
def (other)
Foo.new(to_i other.to_i)
end
end
Foo.new(5) 4
#=> #<Foo:0x00007fbd22050640 @value=9>
為了將 的實體添加Foo到整數,您還必須實作coercewhich 將左側值作為引數并回傳一個將兩個值都轉換為Foo實體的陣列,例如:
class Foo
# ...
def coerce(other)
[Foo.new(other.to_i), self]
end
end
這給你:
4 Foo.new(5)
#=> #<Foo:0x00007fba600e3e28 @value=9>
Numeric包含另一個示例的檔案。
在內部,如果引數不是整數,coerce則呼叫Integer# :(C 代碼)
VALUE
rb_int_plus(VALUE x, VALUE y)
{
if (FIXNUM_P(x)) {
return fix_plus(x, y);
}
else if (RB_TYPE_P(x, T_BIGNUM)) {
return rb_big_plus(x, y);
}
return rb_num_coerce_bin(x, y, ' ');
}
rb_num_coerce_bin呼叫coerce,然后 對回傳的值呼叫二元運算子。
在 Ruby 中,這將是:(簡化)
class Integer
def (other)
if other.is_a?(Integer)
# ...
else
x, y = other.coerce(self)
x y
end
end
end
uj5u.com熱心網友回復:
您仍然需要呼叫該to_int方法,否則解釋器怎么知道您想要做什么?
>> 3 a.to_int
Ruby 不進行自動轉換。
>> 3 "5"
即使 "5" 有一個非常好的 to_i 方法,這也會產生相同的錯誤。順便提一句。to_i如果您想保持一致性,通常會呼叫 ruby?? 中的 int 方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/321212.html
