From 22ed9971304dfcc11eecd7eaa54197cd1a7b0750 Mon Sep 17 00:00:00 2001 From: pdynowski Date: Mon, 18 Jan 2016 13:44:38 -0600 Subject: [PATCH] Implement fixed array --- source/fixed_array.rb | 24 ++++++++++++++++++++++++ source/fixed_array_spec.rb | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/source/fixed_array.rb b/source/fixed_array.rb index 453c307..dfb6fea 100644 --- a/source/fixed_array.rb +++ b/source/fixed_array.rb @@ -1,3 +1,27 @@ class FixedArray + def initialize(size) + @array = Array.new(size) + return @array + end + + def get(index) + check_bounds(index) + @array[index] + end + + def set(index, element) + check_bounds(index) + @array[index] = element + end + + private + def check_bounds(index) + raise OutOfBoundsException, "Index #{index} not in array" if index < 0 || index >= @array.size + end + + class OutOfBoundsException < RangeError + end + end + diff --git a/source/fixed_array_spec.rb b/source/fixed_array_spec.rb index 9b34c5d..29453ca 100644 --- a/source/fixed_array_spec.rb +++ b/source/fixed_array_spec.rb @@ -1,5 +1,40 @@ require_relative 'fixed_array' describe FixedArray do + + describe "#set" do + let(:array) {FixedArray.new(5)} + + it "changes the value at the selected index" do + array.set(2, 4) + values = array.instance_variable_get(:@array) + expect(values[2]).to eq 4 + end + + it "raises an error if the index is outside the array" do + expect { array.set(5, 2)}.to raise_error(RangeError) + expect { array.set(-2, 2)}.to raise_error(RangeError) + end + + end + describe "#get" do + before(:each) do + @array = FixedArray.new(5) + @array.set(2,2) + end + + it "returns the value at the chosen index" do + expect(@array.get(2)).to eq 2 + end + + it "raises an error if an index outside the array is given" do + expect { @array.get(5)}.to raise_error(RangeError) + expect { @array.get(-1)}.to raise_error(RangeError) + end + + end + + + end