Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Creating multi-dimensional hashes in Ruby (See related posts)

The use of var = keys.shift (instead of var = keys_clone || keys.shift) will produce an alternative output!


class Hash
  def mdh(*mkeys)
     value = mkeys.pop
     count = 0
     mdhash = lambda { |*keys|
                   count += 1
                   keys_clone = keys.clone if count == 1 # keys_clone will return nil for count > 1 in Hash.new
                   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)
puts h[k][k[0]][k[1]][k[2]][k[3]]  # value


     

You need to create an account or log in to post comments to this site.


Click here to browse all 5140 code snippets

Related Posts