Skip to content

Instantly share code, notes, and snippets.

@brunops
Created September 2, 2015 06:44
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 brunops/14ee309d3fa2f61477a8 to your computer and use it in GitHub Desktop.
Save brunops/14ee309d3fa2f61477a8 to your computer and use it in GitHub Desktop.
CONF = {
:group1 => {
:a => 'a',
:b => 'b',
:c => 'c'
},
:group2 => {
:aa => 1,
:bb => 'bb'
}
}
class MMHash < Hash
def method_missing name, *args, &block
self[name]
end
def [] index
if index.is_a? String
self[index.to_sym]
else
super
end
end
end
conf = MMHash.new
CONF.keys.each do |group|
conf[group] = MMHash.new
CONF[group].keys.each do |prop|
conf[group][prop] = CONF[group][prop]
end
end
p conf # => {:group1=>{:a=>"a", :b=>"b", :c=>"c"}, :group2=>{:aa=>1, :bb=>"bb"}}
p conf[:group1] # => {:a=>"a", :b=>"b", :c=>"c"}
p conf[:group1][:a] # => "a"
p conf[:group1][:t] # => nil
p conf.group10 # => nil
p conf.group1 # => {:a=>"a", :b=>"b", :c=>"c"}
p conf.group1.aa # => nil
p conf['group10'] # => nil
p conf['group1'] # => {:a=>"a", :b=>"b", :c=>"c"}
p conf['group1'].aa # => nil
p conf['group1'].a # => "a"
p conf.group10.aaa # => Ideally this would be `nil`, but it seems impossible
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment