Skip to content

Instantly share code, notes, and snippets.

@msrose
Last active November 8, 2016 22:55
Show Gist options
  • Save msrose/63f1bb4e5774da7c2b8dc226204c35d0 to your computer and use it in GitHub Desktop.
Save msrose/63f1bb4e5774da7c2b8dc226204c35d0 to your computer and use it in GitHub Desktop.
Using ruby blocks to write a map function
# 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