Skip to content

Instantly share code, notes, and snippets.

@yudapc
Last active November 18, 2015 02:34
Show Gist options
  • Save yudapc/a9ee204eff25da09c626 to your computer and use it in GitHub Desktop.
Save yudapc/a9ee204eff25da09c626 to your computer and use it in GitHub Desktop.
Ruby - Hash to Object
class Hashit
def initialize(hash)
hash.each do |k,v|
self.instance_variable_set("@#{k}", v.is_a?(Hash) ? Hashit.new(v) : v)
self.class.send(:define_method, k, proc{self.instance_variable_get("@#{k}")})
self.class.send(:define_method, "#{k}=", proc{|v| self.instance_variable_set("@#{k}", v)})
end
end
end
example of use
h = Hashit.new({a: '123r', b: {c: 'sdvs'}})
h.a
"123r"
h.b.c
"sdvs"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment