I personally use the recursive-open-struct gem - it is as simple as RecursiveOpenStruct.new(<nested_hash>)
But for recursion practice, I will show you a fresh solution:
require 'ostruct' def to_recursive_ostruct(hash) OpenStruct.new(hash.each_with_object({}) do |(key, val), memo| memo[key] = val.is_a?(Hash) ? to_recursive_ostruct(val) : val end) end puts to_recursive_ostruct(a: { b: 1}).ab
edit
the reason this is better than JSON-based solutions is that you may lose some data when converting to JSON. For example, if you convert a Time object to JSON and then parse it, it will be a string. There are many other examples of this:
class Foo; end JSON.parse({obj: Foo.new}.to_json)["obj"] # => "#<Foo:0x00007fc8720198b0>"
yes ... not super helpful. You have completely lost your link to the actual instance.
max pleaner
source share