I am aware of this feature provided by ActiveSupport.
h = ActiveSupport::OrderedOptions.new
h.boy = 'John'
h.girl = 'Mary'
h.boy # => 'John'
h.girl # => 'Mary'
However I already have a large hash and I want to access that hash using dot notation. This is what I tried:
large_hash = {boy: 'John', girl: 'Mary'}
h = ActiveSupport::OrderedOptions.new(large_hash)
h.boy # => nil
That did not work. How can I make this work.
I am using ruby 1.9.2
Update:
Sorry I should have mentioned that I can't use openstruct because it does not have each_pair method which Struct has. I do not know keys beforehand so I can't use openstruct.
I created my own gem for this, and I've been using it in all my projects. Seems to do just what you need:
Would love some feedback.
If it’s just a small script it’s safe to extend
Hash
itselfmethod_missing
is a magic method that is called whenever your code tries to call a method that does not exist. Ruby will intercept the failing call at run time and let you handle it so your program can recover gracefully. The implementation above tries to access the hash using the method name as a symbol, the using the method name as a string, and eventually fails with Ruby's built-in method missing error.For a more complex application, where adding this behavior to all hashes might break other code or third0party gems, use a module and extend each instance
and for greater convenience you can even propagate the module down to nested hashes
You are looking for OpenStruct
OpenStruct should work nicely for this.
If you want to see how it works, or perhaps make a customized version, start with something like this: