From: "trans (Thomas Sawyer)" Date: 2012-11-18T20:35:40+09:00 Subject: [ruby-core:49521] [ruby-trunk - Feature #7341] Enumerable#associate Issue #7341 has been updated by trans (Thomas Sawyer). =begin One problem I have with this is the terminology. The term "associate" already applies to arrays. ((*Associative arrays*)) are arrays of arrays where the first element of an inner array acts a key for the rest. [[:a,1],[:b,2]].assoc(:a) #=> [:a,1] For this reason I would expect an #associate method to take a flat array and group the elements together. [:a,1,:b,2].associate #=> [[:a,1],[:b,2]] An argument could determine the number elements in each group, the default being 2. Since Hash#to_a returns an associative array, to me it makes sense that Array#to_h would reverse the process. {:a=>1,:b=>2}.to_a #=> [[:a,1],[:b,2]] [[:a,1],[:b,2]].to_h #=> {:a=>1,:b=>2} Putting the two together, your version of associate is easy enough to achieve: [:a,1,:b,2].associate.to_h As it turns out, with the exception of the default argument, #associate is same as #each_slice. But I think it would be nice to have #associate around for it's default and the fact that it reads better in these cases. =end ---------------------------------------- Feature #7341: Enumerable#associate https://bugs.ruby-lang.org/issues/7341#change-33053 Author: nathan.f77 (Nathan Broadbent) Status: Open Priority: Normal Assignee: Category: core Target version: next minor Jeremy Kemper proposed Enumerable#associate during the discussion in #7297, with the following details: ------------------- Some background: #4151 proposes an Enumerable#categorize API, but it's complex and hard to understand its behavior at a glance. #7292 proposes an Enumerable#to_h == Hash[...] API, but I don't think of association/pairing as explicit coercion, so #to_h feels misfit. Associate is a simple verb with unsurprising results. It doesn't introduce ambiguous "map" naming. You associate an enumerable of keys with yielded values. Some before/after examples: Before: Hash[ filenames.map { |filename| [ filename, download_url(filename) ]}] After: filenames.associate { |filename| download_url filename } # => {"foo.jpg"=>"http://...", ...} Before: alphabet.each_with_index.each_with_object({}) { |(letter, index), hash| hash[letter] = index } After: alphabet.each_with_index.associate # => {"a"=>0, "b"=>1, "c"=>2, "d"=>3, "e"=>4, "f"=>5, ...} Before: keys.each_with_object({}) { |k, hash| hash[k] = self[k] } # a simple Hash#slice After: keys.associate { |key| self[key] } ------------------- It's worth noting that this would compliment ActiveSupport's Enumerable#index_by method: http://api.rubyonrails.org/classes/Enumerable.html#method-i-index_by #index_by produces '{ => el, ...}', while #associate would produce '{el => , ...}'. For cases where you need to control both keys and values, you could use '[1,2,3].map{|i| [i, i * 2] }.associate', or continue to use 'each_with_object({})'. -- http://bugs.ruby-lang.org/