Issue #5008 has been updated by Thomas Sawyer.


"Repeating myself, unlike other classes in the table, Hash does not have "natural" conversion from set of values, so that I don't think it's worth provide to_h method."

What does that even mean?

From a practical vantage, I use #to_h all the time and constantly have to define it in my projects. I just did it a few minutes ago, in fact. The need stems from polymorphic behaviour on data mappings.

    def some_method(data)
      data = data.to_h
      # ... now I have a known data object to work with ...
    end

Anything that responds to #to_h can be passed. Without that we would have to account for every possible type, which is very limiting and basically not practical.

While #to_hash could be used, as with the other conversion methods, it conveys the object is a Hash in it's very essence --not simply an object that can fashion a hash from itself regardless of how. An object that responds to #to_hash, otoh, would almost certainly respond to #[], #[]= and #each and probably #key?, #keys and #values, too. Although obviously there is no necessary set of public methods it must provide. But is a much stronger indication of the object's nature.

Another use case is simple serialization. #to_h is hand-dandy for converting representation of objects to JSON. Again, something like Contact#to_h is perfectly useful and sensible, where as Contact#to_hash just doesn't jive.

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

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/