Permalink
Browse files

Support for first(n)

This should Resolve #13.

It uses the same pattern as Array#first that accepts an argument.

The first `n` elements of the array are returned, each of them has
  the potential to raise an IndexError.

Example:

```ruby
arr = Fetching([1,2,3])
arr.first(2)
=> [1,2]
arr.first(5)
=> IndexError: index 3 outside of array bounds: -3...3
```
  • Loading branch information...
yez committed Jan 7, 2016
1 parent b4236ed commit 749624e89100066e514b0521ea69f2e91a226309
Showing with 18 additions and 6 deletions.
  1. +4 −2 lib/fetching/fetching_array.rb
  2. +14 −4 spec/fetching/fetching_array_spec.rb
@@ -13,8 +13,10 @@ def each
end
end
def first
self[0]
def first(num = 0)
return self[0] if num.zero?
num.times.map { |i| self[i] }
end
module ArrayMethods
@@ -21,10 +21,20 @@
end
end
specify '#first' do
ary = []
sassy_ary = Fetching(ary)
expect { sassy_ary.first }.to raise_error(IndexError)
describe '#first' do
it 'returns the first element in the array' do
ary = []
sassy_ary = Fetching(ary)
expect { sassy_ary.first }.to raise_error(IndexError)
end
context 'when passed an amount to fetch the first of' do
it 'returns the first n elements' do
ary = [1, 2, 3]
sassy_ary = Fetching(ary)
expect(sassy_ary.first(2)).to eq([1, 2])
end
end
end
describe 'array methods' do

0 comments on commit 749624e

Please sign in to comment.