Skip to content

Instantly share code, notes, and snippets.

@jimweirich
Created February 7, 2012 11:54
Show Gist options
  • Save jimweirich/1759340 to your computer and use it in GitHub Desktop.
Save jimweirich/1759340 to your computer and use it in GitHub Desktop.
Vital Ruby my_each
class Array
def my_each
i = 0
while i < self.length
yield self[i]
i += 1
end
self[0]
end
def my_map
result = []
each do |item|
result << yield(item)
end
result
end
def my_inject(initial=nil)
acc = initial
my_each do |item|
if acc.nil?
acc = item
else
acc = yield(acc, item)
end
end
acc
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_map" do
it "maps each value to a new value" do
result = array.my_map { |item| item * 2 }
result.should == [2,4,6,8]
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