Last active
July 8, 2016 07:59
-
-
Save nykma/e14e2b1dc5d624643618230fb35d516b to your computer and use it in GitHub Desktop.
Pointer for Ruby array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Pointer | |
attr_reader :count, :array, :current, :index | |
def initialize(array) | |
raise unless array.is_a?(Array) | |
@array = array.clone | |
@count = @array.count | |
@current = @array.first | |
@index = 0 | |
end | |
def next | |
return nil if @index >= @count | |
@index += 1 | |
@current = @array[@index] | |
end | |
def reset | |
@index = 0 | |
@current = @array[0] | |
end | |
def inspect | |
"#<Pointer array=#{@array.inspect} current=#{@current}>" | |
end | |
alias :value :current | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RSpec.describe Pointer do | |
describe '.initialize' do | |
it 'should initialize a pointer' do | |
array = [1,2,3,4,5] | |
pointer = Pointer.new(array) | |
expect(pointer.current).to eq 1 | |
expect(pointer.count).to eq 5 | |
expect(pointer.index).to eq 0 | |
end | |
it { expect {Pointer.new('test')}.to raise_error } | |
end | |
describe '.next' do | |
it 'should move pointer to next' do | |
array = [1,2,3] | |
pointer = Pointer.new(array) | |
expect(pointer.current).to eq 1 | |
expect(pointer.next).to eq 2 | |
expect(pointer.current).to eq 2 | |
expect(pointer.next).to eq 3 | |
expect(pointer.current).to eq 3 | |
expect(pointer.next).to eq nil | |
expect(pointer.current).to eq nil | |
expect(pointer.next).to eq nil | |
expect(pointer.current).to eq nil | |
expect(pointer.index).to eq 3 | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment