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
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.
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.
Glad to help!