Skip to content

Instantly share code, notes, and snippets.

@npras
Created July 3, 2012 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npras/3037901 to your computer and use it in GitHub Desktop.
Save npras/3037901 to your computer and use it in GitHub Desktop.
Re-implementing the iterators
class Array
def my_map(&nameless_fn)
new_arr = []
return Enumerator.new(self, :my_map) unless nameless_fn
self.each do |x|
new_arr << nameless_fn.call(x)
end
new_arr
end
def my_map!(&nameless_fn)
return Enumerator.new(self, :my_map!) unless nameless_fn
self.each_with_index do |x, i|
self[i] = nameless_fn.call(x)
end
end
def my_select(&nameless_fn)
new_arr = []
self.each do |x|
new_arr << x if nameless_fn.call(x)
end
new_arr
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment