Commit fd949663 authored by Yukihiro Matsumoto's avatar Yukihiro Matsumoto

Enumerable#inject should handle empty enumerable; http://www.tbn.co.jp/blog/?p=813

parent ac3b1c4c
...@@ -200,13 +200,18 @@ module Enumerable ...@@ -200,13 +200,18 @@ module Enumerable
# ISO 15.3.2.2.11 # ISO 15.3.2.2.11
def inject(*args, &block) def inject(*args, &block)
raise ArgumentError, "too many arguments" if args.size > 2 raise ArgumentError, "too many arguments" if args.size > 2
flag = true # 1st element? if args.empty?
result = nil flag = true # no initial argument
result = nil
else
flag = false
result = args[0]
end
self.each{|val| self.each{|val|
if flag if flag
# 1st element # push first element as initial
result = (args.empty?)? val: block.call(args[0], val)
flag = false flag = false
result = val
else else
result = block.call(result, val) result = block.call(result, val)
end end
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment