Skip to content

Instantly share code, notes, and snippets.

@abhionlyone
Created October 10, 2018 16:07
Show Gist options
  • Save abhionlyone/df5e1c9930c3ef49247628baa4d9196d to your computer and use it in GitHub Desktop.
Save abhionlyone/df5e1c9930c3ef49247628baa4d9196d to your computer and use it in GitHub Desktop.
Ruby - Convert a Hash into 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
@abhionlyone
Copy link
Author

@abhionlyone
Copy link
Author

This service class helps you to convert a Hash into an object so that you can access all the values like object.key_name instead of hash[:key_name]

@abhionlyone
Copy link
Author

Ruby also has inbuilt support for this kind of requirement. OpenStruct is a Ruby data structure made specifically for these kinds of situations. It employs a hash internally to save attribute values. More here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment