Project

General

Profile

Actions

Feature #5662

closed

inject-accumulate, or Haskell's mapAccum*

Added by EdvardM (Edvard Majakari) almost 13 years ago. Updated over 12 years ago.

Status:
Rejected
Assignee:
-
Target version:
-
[ruby-core:41212]

Description

with Ruby, we often use this idiom to build a hash out of something:

new_hash = enum.inject({}) { |h, thing| h[compute_key(thing) = compute_value(thing)]; h }

while that last h is very easy to add, it is also easy to forget and feels logically not very injectish thing to do. I'd propose this we call 'infuse' in our project:

module Enumerable

like inject, but returns accumulator instead. Instead of writing

[1, 2].inject({}) {|h, i| h[i] = 2*i; h }

just say

[1, 2].infuse({}) {|h, i| h[i] = 2*i } # -> {1 => 2, 2 => 4}

def infuse(init, &block)
inject(init) { |acc, i| block.call(acc, i); acc }
end
end

Eg. [1, 2].infuse({}) { |a, i| a[i] = 2*i } # => {1 => 2, 2 => 4}

Instead of infuse, maybe inject_accum or inject_acc would be more rubyish method name.


Related issues 1 (0 open1 closed)

Related to Ruby master - Feature #4151: Enumerable#categorizeRejectedakr (Akira Tanaka)Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0