Issue #3131 has been updated by Koichi Sasada.


Who should work on it?
----------------------------------------
Feature #3131: add Kernel#Hash() method like Kernel#Array()
https://bugs.ruby-lang.org/issues/3131

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


=begin
 Hello,
 
 There is an imbalance of power in the Ruby core API (when it comes 
 to arrays and hashes) because it is easier to convert nil values 
 into empty arrays, thanks to Kernel#Array(), than it is to convert 
 nil values into empty hashes, due to lack of Kernel#Hash().
 
 To correct this asymmetry and restore a balance of power, please
 add a Kernel#Hash() method for converting nil, Array, and Hash
 values into hashes:
 
     module Kernel
       def Hash(value)
         if value.respond_to? :to_hash
           value.to_hash
         elsif value.respond_to? :to_ary
           Hash[*value.to_ary]
         elsif value.nil?
           {}
         else
           raise ArgumentError, "invalid value for Hash: #{value}"
         end
       end
     end
 
 For example, here is how I would use the above API:
 
     #-------------------------------------------------------------------------
     # CASE 1: to_hash
     #-------------------------------------------------------------------------
     
     real_hash = {:real => true}
     Hash(real_hash) # => {:real=>true}
 
     fake_hash = Object.new
     def fake_hash.to_hash
       {:fake => true}
     end
     Hash(fake_hash) # => {:fake=>true}
 
     #-------------------------------------------------------------------------
     # CASE 2: to_ary
     #-------------------------------------------------------------------------
     
     real_array = [:real, true]
     Hash(real_array) # => {:real=>true}
 
     fake_array = Object.new
     def fake_array.to_ary
       [:fake, true]
     end
     Hash(fake_array) # => {:fake=>true}
 
     #-------------------------------------------------------------------------
     # CASE 3: nil
     #-------------------------------------------------------------------------
 
     Hash(nil) # => {}
 
     #-------------------------------------------------------------------------
     # CASE 4: unsupported arguments
     #-------------------------------------------------------------------------
     
     >> Hash(true)
     ArgumentError: invalid value for Hash: true
             from (irb):74:in `Hash'
             from (irb):80
             from /usr/bin/irb:12:in `<main>'
 
     >> Hash(false)
     ArgumentError: invalid value for Hash: false
             from (irb):74:in `Hash'
             from (irb):81
             from /usr/bin/irb:12:in `<main>'
 
     >> Hash(123)
     ArgumentError: invalid value for Hash: 123
             from (irb):74:in `Hash'
             from (irb):82
             from /usr/bin/irb:12:in `<main>'
 
 Thanks for your consideration.
=end



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