Skip to content

Commit 5b36167

Browse files
committed
Simplify Enumerable#inject method
1 parent 9b4e6b8 commit 5b36167

File tree

1 file changed

+20
-10
lines changed

1 file changed

+20
-10
lines changed

src/main/ruby/truffleruby/core/enumerable.rb

Lines changed: 20 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -505,24 +505,32 @@ def sort_by
505505
sort_values.map! { |ary| ary.value }
506506
end
507507

508+
# Enumerable#inject
509+
# inject(symbol) -> object
510+
# inject(initial_operand, symbol) -> object
511+
# inject {|memo, operand| ... } -> object
512+
# inject(initial_operand) {|memo, operand| ... } -> object
508513
def inject(initial=undefined, sym=undefined, &block)
509514
if Array === self
510515
return Primitive.array_inject(self, initial, sym, block)
511516
end
512517

513-
if !Primitive.undefined?(sym) && block_given?
514-
warn 'given block not used', uplevel: 1
518+
# inject()
519+
if !block_given? && Primitive.undefined?(initial)
520+
raise ArgumentError, 'no block or symbol given'
515521
end
516522

517-
if !block_given? or !Primitive.undefined?(sym)
518-
if Primitive.undefined?(sym)
519-
raise ArgumentError, 'no block or symbol given' if Primitive.undefined?(initial)
520-
sym = initial
521-
initial = undefined
522-
end
523+
# inject(initial_operand, symbol) { ... }
524+
if block_given? && !Primitive.undefined?(sym)
525+
warn 'given block not used', uplevel: 1
526+
end
523527

524-
# Do the sym version
528+
unless Primitive.undefined?(sym) && block_given?
529+
# Do the sym version:
530+
# inject(symbol) -> object
531+
# inject(initial_operand, symbol) -> object
525532

533+
sym, initial = initial, undefined if Primitive.undefined?(sym)
526534
sym = sym.to_sym
527535

528536
each do
@@ -534,7 +542,9 @@ def inject(initial=undefined, sym=undefined, &block)
534542
end
535543
end
536544

537-
# Block version
545+
# Do the block version:
546+
# inject {|memo, operand| ... } -> object
547+
# inject(initial_operand) {|memo, operand| ... } -> object
538548
else
539549
each do
540550
o = Primitive.single_block_arg

0 commit comments

Comments
 (0)