Hash to Object

Sometimes I have the need to create objects that responds to some methods with a specific values.
Something that I can use like
HashObject.new :method1 => value_for_method1, :method2 => value_for_method2
There is already a way to do it, with OpenStruct, but I created a HashObject. Just for academic proposals. I didn’t knew the OpenStruct at the time.

class HashObject
  def initialize(hash)
    hash.each do |k,v|
      self.instance_variable_set("@#{k}", 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

  def to_hash
    hash_to_return = {}
    self.instance_variables.each do |var|
      hash_to_return[var.gsub("@","")] = self.instance_variable_get(var)
    end
    return hash_to_return
  end
end

3 Responses to “Hash to Object”


  1. 1 Leonardo Borges April 25, 2009 at 15:26

    If I understood correctly, you can use an OpenStruct for it:

    irb(main):001:0> require ‘ostruct’
    => true
    irb(main):002:0> o = OpenStruct.new
    => #
    irb(main):003:0> o.name = “Leo”
    => “Leo”
    irb(main):004:0> o.name
    => “Leo”

    It is actually implemented with a hash.

  2. 2 Miguel Regedor April 25, 2009 at 16:47

    yes! Thanks, you are right.. I was reinventing the wheel.
    I can do:
    irb(main):001:0> require ‘ostruct’
    => true
    irb(main):002:0> o = OpenStruct.new :name => “miguel”, :age => 22
    => #
    irb(main):003:0> o.name
    => “miguel”
    irb(main):004:0> o.age
    => 22

    Thanks again for the tip.


Leave a Reply




Last Regedor’s twitts

Last Regedor's bookmarks