Skip to content

Instantly share code, notes, and snippets.

@ryanswood
Created July 15, 2014 20:54
Show Gist options
  • Select an option

  • Save ryanswood/651479bb420c80ff4439 to your computer and use it in GitHub Desktop.

Select an option

Save ryanswood/651479bb420c80ff4439 to your computer and use it in GitHub Desktop.
Reduce / Inject
class Array
def my_inject(*args)
acc = args.length >= 1 ? args[0] : self.shift
self.each {|el| acc = yield acc, el}
acc
end
end
def assert_equal(actual, expected)
puts "You expected #{expected} and got #{actual}" unless actual == expected
end
assert_equal([1,2,3,4].my_inject(0) { |sum, el| sum + el }, 10) # w/ a initial
assert_equal([1,2,3,4].my_inject { |sum, el| sum + el }, 10) # w/o a initial
assert_equal([1,2,3,4].my_inject(0) { |sum, el| sum * el }, 0) # w/ a initial
assert_equal([1,2,3,4].my_inject { |sum, el| sum * el }, 24) # w/o a initial
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment