From: Suraj Kurapati Date: 2011-09-26T05:22:58+09:00 Subject: [ruby-core:39706] [Ruby 1.9 - Feature #3131] add Kernel#Hash() method like Kernel#Array() Issue #3131 has been updated by Suraj Kurapati. Any chance of this getting into Ruby 1.9.3? Thanks. ---------------------------------------- Feature #3131: add Kernel#Hash() method like Kernel#Array() http://redmine.ruby-lang.org/issues/3131 Author: Suraj Kurapati Status: Assigned Priority: Normal Assignee: Yukihiro Matsumoto Category: core Target version: 1.9.x =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 `
' >> Hash(false) ArgumentError: invalid value for Hash: false from (irb):74:in `Hash' from (irb):81 from /usr/bin/irb:12:in `
' >> Hash(123) ArgumentError: invalid value for Hash: 123 from (irb):74:in `Hash' from (irb):82 from /usr/bin/irb:12:in `
' Thanks for your consideration. =end -- http://redmine.ruby-lang.org