Project

General

Profile

Actions

Feature #666

closed

Enumerable::to_hash

Added by marcandre (Marc-Andre Lafortune) about 16 years ago. Updated almost 11 years ago.

Status:
Rejected
Target version:
[ruby-core:19397]

Description

=begin
There are many ways to obtain an array from enumerables (to_a, map, ...).
There is no natural way to obtain a hash from an enumerable (except for Hash[some_array]).
There is a Hash::to_a but no Array::to_hash.
Here is what I would like:

[[:hello, "world"], [:choice, [:red_pill, :blue_pill]]].to_hash ==> {:hello=>"world", :choice=>[:red_pill, :blue_pill]}
(1..3).to_hash{|n| [n, n**2]} ==> {1 => 1, 2 ==> 4, 3 ==> 9}

I propose to add the following Enumerable::to_hash :

module Enumerable
def to_hash
result = {}
self.each do |key, value|
key, value = yield(key, value) if block_given?
result[key] = value
end
result
end
end

Since Hash::to_a returns an array of key-value pairs, I fell it's natural that a block to construct a Hash should return key-value pairs.
This definition has nice symmetric properties: for any Hash h, the following all return a copy of h.
h.to_a.to_hash
h.to_hash{|p| p}
h.to_hash{|k,v| [k,v]}
h.keys.zip(h.values).to_hash

Thank you for your attention,

Marc-Andre Lafortune
=end


Related issues 3 (0 open3 closed)

Related to Ruby master - Feature #4151: Enumerable#categorizeRejectedakr (Akira Tanaka)Actions
Related to Ruby master - Feature #7292: Enumerable#to_hClosedmarcandre (Marc-Andre Lafortune)11/07/2012Actions
Has duplicate Ruby master - Feature #7241: Enumerable#to_h proposalRejected10/30/2012Actions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0