class Basic101::BasicArray

Public Class Methods

new(num_dimensions, default) click to toggle source
# File lib/basic101/basic_array.rb, line 7
def initialize(num_dimensions, default)
  @default = default
  dimension [10] * num_dimensions
end

Public Instance Methods

dimension(max_indices) click to toggle source
# File lib/basic101/basic_array.rb, line 12
def dimension(max_indices)
  check_max_indices(max_indices)
  @max_indices = max_indices
  @array = make_array(max_indices)
end
get(indices) click to toggle source
# File lib/basic101/basic_array.rb, line 18
def get(indices)
  check_indices(indices)
  array_get(@array, indices)
end
set(indices, value) click to toggle source
# File lib/basic101/basic_array.rb, line 23
def set(indices, value)
  check_indices(indices)
  array_set(@array, value, indices)
end

Private Instance Methods

array_get(a, indices) click to toggle source
# File lib/basic101/basic_array.rb, line 40
def array_get(a, indices)
  if indices.size == 0
    a
  else
    array_get(a[indices.first.to_i], indices[1..-1])
  end
end
array_set(a, value, indices) click to toggle source
# File lib/basic101/basic_array.rb, line 48
def array_set(a, value, indices)
  if indices.size == 1
    a[indices.first] = value
  else
    array_set(a[indices.first], value, indices[1..-1])
  end
end
check_indices(indices) click to toggle source
# File lib/basic101/basic_array.rb, line 62
def check_indices(indices)
  raise IndexError unless indices.size == @max_indices.size
  indices.zip(@max_indices).each do |index, dimension|
    raise IndexError unless (0..dimension).include?(index)
  end
end
check_max_indices(max_indices) click to toggle source
# File lib/basic101/basic_array.rb, line 56
def check_max_indices(max_indices)
  max_indices.each do |max_index|
    raise ArraySizeError if max_index < 0
  end
end
make_array(max_indices) click to toggle source
# File lib/basic101/basic_array.rb, line 30
def make_array(max_indices)
  if max_indices.size == 0
    @default
  else
    Array.new(max_indices.first + 1) do
      make_array(max_indices[1..-1])
    end
  end
end