Gra*_*dpa 11
我们可以!
class MyArray
include Enumerable
def initialize
@size = 0
end
def <<(val)
instance_variable_set("@a#{@size}".to_sym, val)
@size += 1
end
def [](n)
instance_variable_get("@a#{n}")
end
def length
@size
end
def each
0.upto(@size - 1) { |n| yield self[n] }
end
end
a = MyArray.new
a << 1
a << 2
p a.to_a #=> [1,2]
Run Code Online (Sandbox Code Playgroud)
这可以通过在对象上创建实例变量@ a0,@ a1等来表示数组索引0,1等.它具有恒定的时间长度和索引操作.其余的操作(删除等)需要更多努力才能实现,但这绝对是可能的.
请注意,索引操作的常量时间属性取决于使用适用于实例变量的数据结构的基础Ruby运行时.