Skip to content

Instantly share code, notes, and snippets.

@Fluxx
Created October 18, 2011 04:17
Show Gist options
  • Select an option

  • Save Fluxx/1294602 to your computer and use it in GitHub Desktop.

Select an option

Save Fluxx/1294602 to your computer and use it in GitHub Desktop.
require "rspec"
class Array
def amap
return to_enum(:amap) unless block_given?
self.class.new.tap do |arr|
each { |i| arr << yield(i) }
end
end
end
describe Array do
describe '#amap' do
let(:array) { [1,2,3,4,5] }
let(:add_one) { array.amap { |i| i + 1 } }
it 'returns a new array instance' do
add_one.object_id.should_not == array.object_id
end
it 'yields each element to the block' do
count = 0
array.amap { |i| count += 1 }
count.should == array.length
end
it 'returns a new array made by results of calling each block' do
add_one.should == [2,3,4,5,6]
end
it 'works on an empty array' do
[].amap { |i| i + 5 }.should == []
end
it 'returns an Enumerator if no block is given' do
array.amap.should be_an(Enumerator)
end
it 'allows itself to be chained with other collection methods' do
combo = array.amap.with_index { |val, i| "#{i}-#{val}" }
combo.should == %w[0-1 1-2 2-3 3-4 4-5]
end
end
end
__END__
Sample IRB session
1.9.2p290> require 'crowflower_question'
0.6900 => true
1.9.2p290> [1,2,3,4].amap { |i| i + 1 }
0.0002 => [2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment