Skip to content

Instantly share code, notes, and snippets.

@cayblood
Forked from jimweirich/x.rb
Created February 7, 2012 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cayblood/1759362 to your computer and use it in GitHub Desktop.
Save cayblood/1759362 to your computer and use it in GitHub Desktop.
Vital Ruby my_each
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