Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions source/fixed_array.rb
Original file line number Diff line number Diff line change
@@ -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

35 changes: 35 additions & 0 deletions source/fixed_array_spec.rb
Original file line number Diff line number Diff line change
@@ -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