>> a = 5
=> 5
>> b = "hello, world!"
=> "hello, world!"
>> b.dup
=> "hello, world!"
>> a.dup
TypeError: can't dup Fixnum
from (irb):4:in `dup'
from (irb):4
我知道每次将整数分配给新变量时,Ruby 都会进行复制,但为什么会Numeric#dup
引发错误?
这不会破坏抽象,因为所有对象都应该.dup
正确响应吗?
dup
据我所知,重写该方法将解决问题:
>> class Numeric
>> def dup()
>> self
>> end
>> end
这有我没有看到的缺点吗?为什么这不是内置在 Ruby 中的?