Skip to content

Commit a95249e

Browse files
committed
[GR-18163] Simplify Enumerable#inject method
PullRequest: truffleruby/3650
2 parents 573706c + 9e1b437 commit a95249e

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

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

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -505,43 +505,53 @@ 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-
524-
# Do the sym version
523+
# inject(initial_operand, symbol) { ... }
524+
if block_given? && !Primitive.undefined?(sym)
525+
warn 'given block not used', uplevel: 1
526+
end
525527

526-
sym = sym.to_sym
528+
if Primitive.undefined?(sym) && block_given?
529+
# Do the block version:
530+
# inject {|memo, operand| ... } -> object
531+
# inject(initial_operand) {|memo, operand| ... } -> object
527532

528533
each do
529534
o = Primitive.single_block_arg
530535
if Primitive.undefined? initial
531536
initial = o
532537
else
533-
initial = initial.__send__(sym, o)
538+
initial = yield(initial, o)
534539
end
535540
end
536-
537-
# Block version
538541
else
542+
# Do the sym version:
543+
# inject(symbol) -> object
544+
# inject(initial_operand, symbol) -> object
545+
546+
sym, initial = initial, undefined if Primitive.undefined?(sym)
547+
sym = sym.to_sym
548+
539549
each do
540550
o = Primitive.single_block_arg
541551
if Primitive.undefined? initial
542552
initial = o
543553
else
544-
initial = yield(initial, o)
554+
initial = initial.__send__(sym, o)
545555
end
546556
end
547557
end

0 commit comments

Comments
 (0)