Skip to content

Instantly share code, notes, and snippets.

@brianpattison
Last active August 29, 2015 14:14
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 brianpattison/f43d99378916ae3f6a7c to your computer and use it in GitHub Desktop.
Save brianpattison/f43d99378916ae3f6a7c to your computer and use it in GitHub Desktop.
JamonHash.rb
class JamonHash < HashWithIndifferentAccess
def default(key = nil)
if key.is_a?(String) && key.include?(".")
find_value(key.split("."))
else
super
end
end
def find_value(keys)
key = keys.shift
value = self[key]
if keys.length > 0
if value.is_a?(Hash)
value[keys.join(".")]
else
nil
end
else
value
end
end
end
hash = JamonHash.new
hash[:first] = JamonHash.new
hash[:first][:second] = "Hello!"
hash["first"]
# => {"second"=>"Hello!"}
hash["first.second"]
# => "Hello!"
hash["first.second.third"]
# => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment