Last active
December 26, 2015 12:29
-
-
Save ZhouMeichen/7151710 to your computer and use it in GitHub Desktop.
用each实现map方法
This file contains hidden or 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
| # one dimensional array | |
| # yield | |
| class Array | |
| def my_map | |
| arr = [] | |
| each {|n,i| arr << yield(n)} | |
| arr | |
| end | |
| end | |
| # call | |
| class Array | |
| def my_map &block | |
| arr = [] | |
| each {|i| arr << block.call(i)} | |
| arr | |
| end | |
| end | |
| # multidimensional array | |
| # yield | |
| class Array | |
| def my_map | |
| self.each_with_index do |n,i| | |
| self[i] = yield(n) | |
| end | |
| end | |
| end | |
| # call | |
| class Array | |
| def my_map &block | |
| self.each_with_index do |n,i| | |
| self[i] = block.call(n) | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment