Created
May 14, 2018 00:55
-
-
Save podrezo/c13e00005b7d60c4e443dad483515f0b to your computer and use it in GitHub Desktop.
Implement "map" function from ruby's arrays to understand how blocks work
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
require 'minitest/autorun' | |
# Good blog article https://eli.thegreenplace.net/2006/04/18/understanding-ruby-blocks-procs-and-methods | |
# Extends 'Array' adding the pmap method which is equivalent to map | |
class Array | |
# def pmap(&block) | |
# map(&block) | |
# end | |
def pmap(&block) | |
results = [] | |
to_ary.each do |x| | |
results.push(yield(x)) | |
# Also works: | |
# results.push(block.call(x)) | |
end | |
results | |
end | |
end | |
class PmapTest < Minitest::Test | |
def test_empty | |
result = [].pmap { |x| x } | |
assert_equal [], result | |
end | |
def test_simple | |
result = [1, 2, 3].pmap { |x| x + 1 } | |
assert_equal [2, 3, 4], result | |
end | |
def test_simple_amp_syntax | |
result = [1, 0, 2].pmap(&:zero?) | |
assert_equal [false, true, false], result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment