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


I approve `to_h` as explicit conversion to a Hash.

It should be created and implemented for NilClass, Hash, Enumerable, Struct, OpenStruct.

It would also pave the way for more generic hash splat if the proposal is accepted (see [ruby-core:40675])

The implementation proposed by Suraj Kurapati can not be accepted in its current form, though. In particular, there should be no Object/Kernel#to_h (like there is no Object#to_a/to_i), and Hash#to_h should return a new copy for subclasses (like to_a, to_s).

I realize that Matz doesn't like Enumerable#to_h because there is no perfect "natural" mapping. I feel like any choice here is better than no choice. I think it would be fine if `Enumerable#to_h` was equivalent to the key-value pair form of Hash[enum.to_a], but I'll agree with any other sane definition, as long as it's simple.

For more involved cases, I'm still hoping for Enumerable#associate/categorize.

Thanks.
--
Marc-André
----------------------------------------
Feature #5008: Equal rights for Hash (like Array, String, Integer, Float)
https://bugs.ruby-lang.org/issues/5008#change-24625

Author: Suraj Kurapati
Status: Assigned
Priority: Normal
Assignee: Yukihiro Matsumoto
Category: 
Target version: 


=begin
Hello,

I am using ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-linux].

Although Ruby has a rich set of primitive data types and structures, 
the Hash seems neglected in the Ruby API in comparison to its peers:

* String: Object#to_s by API
* Integer: Kernel#Integer by API and Object#to_i by convention
* Float: Kernel#Float by API and Object#to_f by convention
* Array: Kernel#Array by API and Object#to_a by convention
* Hash: Kernel#Hash (issue #3131) and Object#to_hash by convention

In particular, the Hash seems neglected by the Ruby API because:

* Its convention method (#to_hash) is longer than one character (#to_h).
* It did not have a Kernel-level method until recently (see issue #3131).
* It has no methods for conversion from NilClass, unlike #to_s, a, i, f.

Please rectify this un-orthogonality and grant Hash equal rights by:

* Establish #to_h as the convention method for converting objects into Hash.
* Add Kernel#Hash method for converting objects into Hash strictly (see issue #3131).
* Define NilClass#to_h so that we can convert nil into an empty Hash.

Thanks for your consideration.
=end


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