Last active
February 2, 2020 04:05
-
-
Save jeffchao/5267793 to your computer and use it in GitHub Desktop.
Implementation of Enumerable.map() in Ruby
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
# 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