Skip to content

Instantly share code, notes, and snippets.

@annikoff
Last active May 20, 2020 11:39
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 annikoff/2afd21c8c4c4a2b8a113655c05c1ee46 to your computer and use it in GitHub Desktop.
Save annikoff/2afd21c8c4c4a2b8a113655c05c1ee46 to your computer and use it in GitHub Desktop.
CustomEnumerable module
module CustomEnumerable
def map(sym = nil)
return enum_for(:map) if !block_given? && sym.nil?
raise SyntaxError if block_given? && !sym.nil?
result = []
each do |item|
result << (sym.nil? ? yield(item) : item.send(sym))
end
result
end
def find(sym = nil)
return enum_for(:find) if !block_given? && sym.nil?
raise SyntaxError if block_given? && !sym.nil?
each do |item|
return item if sym.nil? ? yield(item) : item.send(sym)
end
nil
end
def reduce(initial_or_sym, sym = nil)
if initial_or_sym.is_a?(Symbol)
operator = initial_or_sym
initial = nil
else
initial = initial_or_sym
operator = sym
end
accumulator = initial
each_with_index do |item, index|
if index.zero? && initial.nil?
accumulator = item
next
end
accumulator = operator.nil? ? yield(accumulator, item) : accumulator.send(operator, item)
end
accumulator
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment