Skip to content

Instantly share code, notes, and snippets.

@eladmeidar
Created June 25, 2013 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eladmeidar/5857066 to your computer and use it in GitHub Desktop.
Save eladmeidar/5857066 to your computer and use it in GitHub Desktop.
Safe hash nesting
class NestedHash < Hash
def [](value, default = NestedHash.new)
self.fetch(value, default)
end
def self.from_hash(other_hash)
nested_hash = NestedHash.new
other_hash.each_pair do |key, val|
if val.is_a?(Hash)
nested_hash[key] = NestedHash.from_hash(val)
else
nested_hash[key] = val
end
end
return nested_hash
end
end
# Setup a regular hash
h = NestedHash.new
h["elad"] = NestedHash.new
h["elad"]["adam"] = NestedHash.new
h["elad"]["adam"]["hungry"] = "always"
# Test non existing value
puts h["elad"]["miki"]["hungry", "no"] # => "no"
# Test Converstions from regular hashes
real_hash = {:elad => {:koko => :awesome}, :adam => {:moko => :no}}
nested = NestedHash.from_hash(real_hash)
# Missing Value
puts nested[:elad][:invalid_key, "not here"] # => "not here"
# Existing value
puts nested[:elad][:koko] # => "awesome"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment