Skip to content

Instantly share code, notes, and snippets.

@rklemme
Created January 10, 2011 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rklemme/772827 to your computer and use it in GitHub Desktop.
Save rklemme/772827 to your computer and use it in GitHub Desktop.
Multi Dimensional Array
class MultiDimensionalArray
def self.[](*dimension_sizes)
new(*dimension_sizes)
end
def self.cube(dimensions, dimension_size)
new(*Array.new(dimensions, dimension_size))
end
def initialize(*dimension_sizes)
@dims = dimension_sizes.dup.freeze
@data = Hash.new 0 # with default value
end
def [](*idx)
index_check(idx)
@data[idx]
end
def []=(*idx, val)
index_check(idx)
@data[idx] = val
end
def default
@data.default
end
def default=(val)
@data.default = val
end
private
def index_check(idxs)
raise ArgumentError, "Wrong number of dimensions: %p" % [idxs] unless idxs.size == @dims.size
@dims.zip idxs do |d,i|
raise ArgumentError, "Wrong index: %p" % i unless 0 <= i && i < d
end
end
end
mda = MultiDimensionalArray[10, 20]
p mda[1,2]
p mda[5,4]=6
mda[5] rescue nil
p mda[5,4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment