Skip to content

Instantly share code, notes, and snippets.

@jin
Last active August 29, 2015 14:07
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 jin/9bb771f157f46dbeb227 to your computer and use it in GitHub Desktop.
Save jin/9bb771f157f46dbeb227 to your computer and use it in GitHub Desktop.
ruby Array#reduce with an initial value
class Array
def reduce(func, init)
if self.length < func.arity
res = nil
elsif self.length == func.arity
res = func.call(*self)
else
res = func.call(self[0], self[1..-1].reduce(func, nil))
end
init.nil? ? res : func.call(init, res)
end
end
Test.assert_equals( ['a','y','!'].reduce(->(x,y){x+y}, 'y'), 'yay!')
Test.assert_equals( ['1','2','3'].reduce(->(x,y){x+y}, '0'), '0123')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment