Skip to content

Instantly share code, notes, and snippets.

@MyExperiments
Last active August 29, 2015 13:56
Show Gist options
  • Save MyExperiments/9045142 to your computer and use it in GitHub Desktop.
Save MyExperiments/9045142 to your computer and use it in GitHub Desktop.
Convert a nested hash into an OpenStruct object.
require 'ostruct'
def deep_ostruct(hash)
if hash
hash.each do |k,v|
hash["#{k}"] = deep_ostruct(v) if v.is_a?(Hash)
end
end
OpenStruct.new(hash)
end
# Here is an example
hash = {
"one" => 1,
"two" => 2,
"three" => 3,
"squares" => {
"one_sq" => 1,
"two_sq" => 4,
"three_sq" => 9
}
}
new_object = deep_ostruct(hash)
new_object.one # => 1
new_object.two # => 2
new_object.squares # => #<OpenStruct one_sq=1, two_sq=4, three_sq=9>
new_object.squares.three_sq # => 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment