Issue #5662 has been updated by Marc-Andre Lafortune.


Hi,

Edvard Majakari wrote:
> Ok.. I'll give real example to show what is typical use case for us:
> 
> hash = MyDatabaseObject.get_all.infuse({}) { |h, r| h[normalize_db_key(r.id, r.name)] = r }

As pointed out, you currently have the choice of:

    get_all.each_with_object({}) { |r, h| h[normalize_db_key(r.id, r.name)] = r }
    Hash[ get_all.map { |r| [normalize_db_key(r.id, r.name), r] } ]

ActiveSupport also gives you:
    get_all.index_by { |r| normalize_db_key(r.id, r.name) }

There is a proposition for Enumerable#associate/categorize in [ruby-core:33683] which would give you:
    get_all.associate { |r| [normalize_db_key(r.id, r.name), r] }

I also feel your infuse proposal is much too close to inject/each_with_object. Moreover, if you need it mostly to create hashes, it might be best to look into a good way to create hashes (like the proposal for associate/categorize).
----------------------------------------
Feature #5662: inject-accumulate, or Haskell's mapAccum*
http://redmine.ruby-lang.org/issues/5662

Author: Edvard Majakari
Status: Open
Priority: Normal
Assignee: 
Category: 
Target version: 


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.


-- 
http://redmine.ruby-lang.org