From: "trans (Thomas Sawyer)" Date: 2013-08-31T21:26:02+09:00 Subject: [ruby-core:56936] [ruby-trunk - Feature #7292] Enumerable#to_h Issue #7292 has been updated by trans (Thomas Sawyer). =begin If you think about it long enough you realize there is a fair bit of incommensurate behavior between different parts of Hash, e.g. (({Hash[]})) takes a flat array, but (({Hash.to_a})) returns an associative array. And the design does seem to consider the types of polymorphism that can occur between Array and Hash very much at all. But without going into all the nitty-gritty of that, suffice to say you can figure the most fitting definition for (({Enumerable#to_h})) is simply: module Enumerable def to_h a = [] each_with_index.each { |e,i| a << i << e } Hash[*a] end end We can answer why in the nicest of ways too: What is it we are converting to a hash table? It is an ((*Enumerable*))! So it only stands to reason that the conversion reflect the ((*enumeration*)). To convert an associative array to a hash, that is a different goal, and as Ruby currently stands, that is best addressed with (({Hash[*assoc.flatten(1)]})). For something better in that regard I would suggest the addition of something like (({Hash.from_assoc(assoc_array)})). =end ---------------------------------------- Feature #7292: Enumerable#to_h https://bugs.ruby-lang.org/issues/7292#change-41493 Author: marcandre (Marc-Andre Lafortune) Status: Feedback Priority: Low Assignee: matz (Yukihiro Matsumoto) Category: core Target version: next minor Now that #to_h is the official method for explicit conversion to Hash, we should also add Enumerable#to_h: Returns a hash for the yielded key-value pairs. [[:name, 'Joe Smith'], [:age, 42]].to_h # => {name: 'Joe Smith', age: 42} With the Ruby tradition of succint documentation I suggest the documentation talk about key-value pairs and there is no need to be explicit about the uninteresting cases like: (1..3).to_h # => {1 => nil, 2 => nil, 3 => nil} [[1, 2], [1, 3]].to_h # => {1 => 3} [[1, 2], []].to_h # => {1 => 2, nil => nil} I see some reactions of people reading about the upcoming 2.0 release like this one: http://globaldev.co.uk/2012/11/ruby-2-0-0-preview-features/#dsq-comment-body-700242476 -- http://bugs.ruby-lang.org/