Created
February 2, 2014 19:22
-
-
Save NotTheUsual/8773400 to your computer and use it in GitHub Desktop.
Rubyist Test - Task 1
This file contains 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 Array | |
def new_inject total=0 | |
# self.each do |i| | |
# total = yield(total, i) | |
# end | |
for i in (0...self.length) | |
total = yield(total, self[i]) | |
end | |
total | |
end | |
# # Neatest | |
# def recursive_inject total=0,array=self.dup,&block | |
# array.empty? ? total : recursive_inject(yield(total, array.shift),array,&block) | |
# end | |
# More readable, I guess... | |
def recursive_inject(total=0, array=self.dup, &block) | |
return total if array.empty? | |
new_total = yield(total, array.shift) | |
recursive_inject(new_total, array, &block) | |
end | |
end | |
describe Array do | |
context "(only dealing with situations where a block is given)" do | |
it "should be able to add up all the numbers in an array" do | |
array = [1,2,3,4] | |
ans = array.new_inject { |memo, i| memo += i } | |
expect(ans).to eq(10) | |
end | |
it "should be able to add up all the numbers in an array with an initial value" do | |
array = [1,2,3,4] | |
ans = array.new_inject(5) { |memo, i| memo += i } | |
expect(ans).to eq(15) | |
end | |
it "should be able to create new arrays" do | |
array = [1,2,3,4] | |
ans = array.new_inject([]) { |memo, i| i.even? ? memo << i : memo } | |
expect(ans).to eq([2,4]) | |
end | |
end | |
context "(doing the same thing recursively)" do | |
it "should be able to add up all the numbers in an array" do | |
array = [1,2,3,4] | |
ans = array.recursive_inject { |memo, i| memo += i } | |
expect(ans).to eq(10) | |
end | |
it "should be able to add up all the numbers in an array with an initial value" do | |
array = [1,2,3,4] | |
ans = array.recursive_inject(5) { |memo, i| memo += i } | |
expect(ans).to eq(15) | |
end | |
it "should be able to create new arrays" do | |
array = [1,2,3,4] | |
ans = array.recursive_inject([]) { |memo, i| i.even? ? memo << i : memo } | |
expect(ans).to eq([2,4]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment