Created
October 10, 2018 16:07
-
-
Save abhionlyone/df5e1c9930c3ef49247628baa4d9196d to your computer and use it in GitHub Desktop.
Ruby - Convert a Hash into Object
This file contains 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
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 |
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]
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
Source: https://stackoverflow.com/questions/26809848/convert-hash-to-object