Skip to content

Instantly share code, notes, and snippets.

@joshsusser
Created May 9, 2012 16:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshsusser/2646288 to your computer and use it in GitHub Desktop.
Save joshsusser/2646288 to your computer and use it in GitHub Desktop.
Challenge: implement enumerable methods using #inject instead of #each.
def collect(&block)
inject([]) { |memo, obj| memo << block.call(obj) }
end
def detect(&block)
inject(nil) { |memo, obj| memo ||= obj if block.call(obj) }
end
def reject(&block)
inject([]) { |memo, obj| block.call(obj) ? memo : memo << obj }
end
def select(&block)
inject([]) { |memo, obj| block.call (obj) ? memo << obj : memo }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment