我需要帮助来理解继承。
class MyArray < Array
end
a = MyArray[1, 2, 3] #=> [1, 2, 3]
b = MyArray[4, 5] #=> [4, 5]
c = a + b #=> [1, 2, 3, 4, 5]
a.class #=> MyArray
b.class #=> MyArray
c.class #=> Array
我不明白为什么相加的结果不是 MyArray
类的实例。
最佳答案
I don't understand why my array "a" is not "MyArray" class after add.
为什么要它(是一个MyArray
)?数组的串联操作被定义为返回一个新的Array
,所以这就是这里发生的事情。 https://ruby-doc.org/core-2.5.3/Array.html#method-i-2B
如果需要,您可以在类中覆盖该操作以返回 MyArray 的实例。不要忘记所有其他类似的方法。
这也是为什么对标准集合进行子类化不是一个好主意的原因。在这里最好使用组合而不是继承。
关于Ruby、类和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54224858/