创建多维hash

class Hash
  def mdh(*mkeys)
    value = mkeys.pop
    count = 0
    mdhash = lambda { |*keys|
      count += 1
      keys_clone = keys.clone if count == 1
      Hash.new(var = keys_clone || keys.shift).update(var => mdhash[*keys] || value) unless keys.empty?
    }
    mdhash.call(*mkeys)
  end
end

 

具体示例:

 

    h = Hash.new.mdh(1, 2, 3, 4, "value")
    puts h.inspect  # => {[1, 2, 3, 4]=>{1=>{2=>{3=>{4=>"value"}}}}}
    k = [1, 2, 3, 4]
    puts h.has_key?(k)  # => true
    puts h[k][k[0]][k[1]][k[2]][k[3]]  # => value

 

你可能感兴趣的:(hash)