K
Kyle Schmitt
I'm wondering what the _right_ way is to go about getting the right
class with inheritance and super()
Take the following class I'm using for a graphing tool: Like the name
says, it creates a fixed size array. The << operator allows you to
use it as if it were a circular queue of sorts, and the size= method
allows you to re-size the array if necessary.
The issue is that while << works fine, the results from + and - return
an Array, not a FixedSizeArray, UNLESS I run the returned value
through a FixedSizeArray.new(), and somehow, that just seems wrong and
wasteful.
Am I crazy? Is that really the right way?
class FixedSizeArray<Array
def initialize(size=1,fill=nil)
#Sizes under one don't make sense
if size.is_a?Array
super(size)
else
super(size,fill)
end
self
end
def size=(newsize)
unless length==newsize
if length > newsize
self.slice!(Range.new(0,length-newsize-1))
elsif length < newsize
self.unshift(*Array.new(newsize-length){0})
end
end
size
end
def <<(data)
self.shift()
super(data)
self
end
def -(data)
#Works, but feels somehow...wasteful and wrong
FixedSizeArray.new(super(data).unshift(*Array.new(size-super(data).length,nil)))
end
def +(data)
#Works, but feels somehow...wasteful and wrong
FixedSizeArray.new(super(data).slice(Range.new(data.length,size+data.length)))
end
end
class with inheritance and super()
Take the following class I'm using for a graphing tool: Like the name
says, it creates a fixed size array. The << operator allows you to
use it as if it were a circular queue of sorts, and the size= method
allows you to re-size the array if necessary.
The issue is that while << works fine, the results from + and - return
an Array, not a FixedSizeArray, UNLESS I run the returned value
through a FixedSizeArray.new(), and somehow, that just seems wrong and
wasteful.
Am I crazy? Is that really the right way?
class FixedSizeArray<Array
def initialize(size=1,fill=nil)
#Sizes under one don't make sense
if size.is_a?Array
super(size)
else
super(size,fill)
end
self
end
def size=(newsize)
unless length==newsize
if length > newsize
self.slice!(Range.new(0,length-newsize-1))
elsif length < newsize
self.unshift(*Array.new(newsize-length){0})
end
end
size
end
def <<(data)
self.shift()
super(data)
self
end
def -(data)
#Works, but feels somehow...wasteful and wrong
FixedSizeArray.new(super(data).unshift(*Array.new(size-super(data).length,nil)))
end
def +(data)
#Works, but feels somehow...wasteful and wrong
FixedSizeArray.new(super(data).slice(Range.new(data.length,size+data.length)))
end
end