Advertisement
Guest User

Untitled

a guest
Sep 2nd, 2015
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.25 KB | None | 0 0
  1. class MMHash < Hash
  2.   def method_missing name, *args, &block
  3.     self[name]
  4.   end
  5.  
  6.   def [] index
  7.     if index.is_a? String
  8.       self[index.to_sym]
  9.     else
  10.       super
  11.     end
  12.   end
  13. end
  14.  
  15.  
  16.  
  17. ##### usage
  18.  
  19. CONF = {
  20.   :group1 => {
  21.     :a => 'a',
  22.     :b => 'b',
  23.     :c => 'c'
  24.   },
  25.  
  26.   :group2 => {
  27.     :aa => 1,
  28.     :bb => 'bb'
  29.   }
  30. }
  31.  
  32.  
  33. class MMHash < Hash
  34.   def method_missing name, *args, &block
  35.     self[name]
  36.   end
  37.  
  38.   def [] index
  39.     if index.is_a? String
  40.       self[index.to_sym]
  41.     else
  42.       super
  43.     end
  44.   end
  45. end
  46.  
  47. conf = MMHash.new
  48.  
  49. CONF.keys.each do |group|
  50.   conf[group] = MMHash.new
  51.   CONF[group].keys.each do |prop|
  52.     conf[group][prop] = CONF[group][prop]
  53.   end
  54. end
  55.  
  56. p conf              # => {:group1=>{:a=>"a", :b=>"b", :c=>"c"}, :group2=>{:aa=>1, :bb=>"bb"}}
  57. p conf[:group1]     # => {:a=>"a", :b=>"b", :c=>"c"}
  58. p conf[:group1][:a] # => "a"
  59. p conf[:group1][:t] # => nil
  60. p conf.group10      # => nil
  61. p conf.group1       # => {:a=>"a", :b=>"b", :c=>"c"}
  62. p conf.group1.aa    # => nil
  63. p conf['group10']   # => nil
  64. p conf['group1']    # => {:a=>"a", :b=>"b", :c=>"c"}
  65. p conf['group1'].aa # => nil
  66. p conf['group1'].a  # => "a"
  67.  
  68. p conf.group10.aaa      # => Ideally this would be `nil`, but it seems impossible
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement