【发布时间】:2017-05-29 22:50:57
【问题描述】:
我希望我的 SomeArray#map 返回 SomeArray 类的“数组”。
class SomeArray < Array
def map
SomeArray.new(super)
end
end
some_array = SomeArray.new(["foo", "bar", "baz"])
p some_array.class #=> SomeArray
p some_array.map { |e| e }.class #=> SomeArray
除了现在我还希望能够使用Enumerator#with_index 实例方法。所以理想情况下,这样的事情会起作用:
some_array.map.with_index { |e, i| e }.class #=> SomeArray
这将如何工作?
我试过了:
class SomeArray < Array
def map
SomeArray.new(super)
end
def with_index(offset = 0)
super
end
end
some_array = SomeArray.new(["foo", "bar", "baz"])
p some_array.class #=> SomeArray
p some_array.map.with_index { |e, i| e }.class #=> no implicit conversion of Enumerator into Integer (TypeError)
但它不起作用。
【问题讨论】:
标签: ruby oop inheritance