Project

General

Profile

Feature #3131

add Kernel#Hash() method like Kernel#Array()

Added by sunaku (Suraj Kurapati) about 10 years ago. Updated over 7 years ago.

Status:
Closed
Priority:
Normal
Target version:
[ruby-core:29462]

Description

=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


Files

kernel-hash.patch (2.06 KB) kernel-hash.patch runpaint (Run Paint Run Run), 09/02/2010 11:03 PM

Related issues

Follows Ruby master - Feature #5008: Equal rights for Hash (like Array, String, Integer, Float)Rejectedmatz (Yukihiro Matsumoto)07/10/2011Actions

Also available in: Atom PDF