public
Created

Challenge: implement enumerable methods using #inject instead of #each.

  • Download Gist
injections.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.