-
-
Save cayblood/1759362 to your computer and use it in GitHub Desktop.
Vital Ruby my_each
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 my_each | |
length.times do |index| | |
yield(self[index]) | |
end | |
end | |
def my_inject(initial_value) | |
accumulator = initial_value || self.dup.shift | |
my_each do |item| | |
accumulator = yield(accumulator, item) | |
end | |
end | |
end | |
describe "My Array Methods" do | |
let(:array) { [1,2,3,4] } | |
describe "#my_each" do | |
it "iterates over each item" do | |
sum = 0 | |
array.my_each do |item| sum += item end | |
sum.should == 10 | |
end | |
end | |
describe "#my_inject" do | |
context "with an explicit initial" do | |
it "injects an operation in the array" do | |
result = array.my_inject(0) { |acc, item| acc + item } | |
result.should == 10 | |
end | |
end | |
context "with an implicit initial" do | |
it "injects an operation in the array" do | |
result = array.my_inject { |acc, item| acc + item } | |
result.should == 10 | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment