Last active
August 29, 2015 13:56
-
-
Save MyExperiments/9045142 to your computer and use it in GitHub Desktop.
Convert a nested hash into an OpenStruct object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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