Last active
November 8, 2016 22:55
-
-
Save msrose/63f1bb4e5774da7c2b8dc226204c35d0 to your computer and use it in GitHub Desktop.
Using ruby blocks to write a map function
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
# built-in map | |
squares = [1,2,3].map do |n| | |
n * n | |
end | |
puts squares | |
# if you wanted to write your own | |
def my_map_method(array) | |
return array.clone unless block_given? | |
results = [] | |
for item in array | |
results.push(yield item) | |
end | |
results | |
end | |
more_squares = my_map_method([1,2,3]) do |n| | |
n * n | |
end | |
puts more_squares | |
# equivalent syntax for blocks, just because: | |
even_more_squares = my_map_method([1,2,3]) { |n| n * n } | |
puts even_more_squares |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment