Skip to content

Instantly share code, notes, and snippets.

@ZhouMeichen
Last active December 26, 2015 12:29
Show Gist options
  • Select an option

  • Save ZhouMeichen/7151710 to your computer and use it in GitHub Desktop.

Select an option

Save ZhouMeichen/7151710 to your computer and use it in GitHub Desktop.
用each实现map方法
# 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