From: John Turner Date: 2006-09-29T21:25:15+09:00 Subject: Re: Accessing Nested Hashes Directly atraver@gmail.com wrote: > This method can be called like this: > > first_name = get_value(params, :body, :user, :name, :given) > > It will traverse the hash and kick back a nil at the first problem it > finds instead of raising an exception, or will return the value if it > actually exists. > > Here's my question, though: is this code efficient? Is there a better > way? Am I missing something fundamental in Ruby that would solve this > without the need for the new method? > I didn't really like the way that method is called, doesn't seem very "ruby" exactly. Came up with the following which is really dirty at the moment but I prefer how it's called. The method_missing in NilClass is kind of unforgivably dirty. Would like to see improvements I guess, but not sure there's really a way to do this nicely: So, yeah, don't use this, but possibly be amused by it anyway: require 'ostruct' class NestStruct < OpenStruct def self.fromNestedHash(h) struct = NestStruct.new(h) struct.marshal_dump.keys.each do |key| if struct.send(key).is_a? Hash struct.send(key.to_s + '=', fromNestedHash(struct.send(key))) end end return struct end def method_missing(m, *args) super(m, args) rescue NoMethodError nil end end class NilClass def method_missing(m, *args) nil end end h = { 'name' => { 'first' => 'Ross' }, 'contact' => { 'phone' => { 'office' => '345345' } } } s = NestStruct.fromNestedHash(h) puts s.contact.phone # => # puts s.contact.phone.office # => 345345 puts s.contact.phone.home # => nil puts s.foo.bar # => nil