Update attributes and OpenStruct

Rails does have the conveniet method update_attributes to update one or more attributes of an ActiveRecord instance. Sometimes this is also very handy for standard Ruby objects and pretty easy to implement:

class MyClass
  attr_accessor :foo, :bar
  def update_attributes(hash)
    hash.each_pair do |key, value|
        self.send("#{key}=", value)
        # do something when an attribute does not exist
        # or simply ignore it

You can now simply do:

my_instance = MyClass.new
my_hash = { :foo => "Isn't it nice?", :bar => "Yes, indeed!" }
my_instance.foo # Isn't it nice?
my_instance.bar # Yes, indeed!

If you just like to initialize a new instance with some hash and make the keys and values available as attributes of that instance, then make sure to also take a look at OpenStruct.

my_instance = OpenStruct.new({ :foo => "Isn't it nice?", :bar => "Yes, indeed!" })
my_instance.foo # Isn't it nice?
my_instance.bar # Yes, indeed!

You can also call any not yet defined attribute accessor of an OpenStuct instance and set its value.

my_instance.not_yet_defined = "Now it is!"
my_instance.not_yet_defined # Now it is!