Skip to content

Instantly share code, notes, and snippets.

@jeffchao
Last active February 2, 2020 04:05
Show Gist options
  • Save jeffchao/5267793 to your computer and use it in GitHub Desktop.
Save jeffchao/5267793 to your computer and use it in GitHub Desktop.
Implementation of Enumerable.map() in Ruby
# Run using rspec.
# e.g.: rspec file_name.rb
require 'rubygems'
require 'rspec'
module Enumerable
def mymap (&block)
return nil if block.nil?
self.each_with_index do |e, i|
self[i] = block.call(e)
end
end
alias :collect :map
end
describe Enumerable do
describe '#mymap' do
let(:arr) { Array(1..5) }
it 'should return nil if no arguments are used' do
arr.mymap.should == nil
end
it 'should return itself if the block does nothing' do
arr.mymap{ |e| e }.should == [1, 2, 3, 4, 5]
end
it 'should return +1 to each element' do
arr.mymap{ |e| e+1 }.should == [2, 3, 4, 5, 6]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment