Skip to content

Instantly share code, notes, and snippets.

@thedeeno
Created January 16, 2015 20:41
Show Gist options
  • Save thedeeno/49e88024f52b0b7482e5 to your computer and use it in GitHub Desktop.
Save thedeeno/49e88024f52b0b7482e5 to your computer and use it in GitHub Desktop.
class SmartHash
def initialize(hash)
hash.each do |key, v|
instance_variable_name = "@#{key}"
if (v.hash?)
self.instance_variable_set(instance_variable_name, SmartHash.new(v))
else
self.instance_variable_set(instance_variable_name, v) ## create and initialize an instance variable for this key/value pair
end
# define the setter, getter
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
def [](key)
self.send(key)
end
end
SmartHash.new(testObject)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment