mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
Enumerable#inject should handle empty enumerable; http://www.tbn.co.jp/blog/?p=813
This commit is contained in:
+9
-4
@@ -200,13 +200,18 @@ module Enumerable
|
||||
# ISO 15.3.2.2.11
|
||||
def inject(*args, &block)
|
||||
raise ArgumentError, "too many arguments" if args.size > 2
|
||||
flag = true # 1st element?
|
||||
result = nil
|
||||
if args.empty?
|
||||
flag = true # no initial argument
|
||||
result = nil
|
||||
else
|
||||
flag = false
|
||||
result = args[0]
|
||||
end
|
||||
self.each{|val|
|
||||
if flag
|
||||
# 1st element
|
||||
result = (args.empty?)? val: block.call(args[0], val)
|
||||
# push first element as initial
|
||||
flag = false
|
||||
result = val
|
||||
else
|
||||
result = block.call(result, val)
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user