From: Sam Smoot Date: 2007-01-20T07:50:10+09:00 Subject: Re: Declaring instance variables dynamically Alex Schearer wrote: > I was curious whether there was any way to do so without employing a > hash table Here you go: > class User > attr_accessor :name > end => nil > me = User.new > me.name = 'Sam' => 'Sam' > you = User.new > you.name = 'Alex' => 'Alex' > you.mood = :happy => NoMethodError... > you.class.send(:attr_accessor, :mood) > you.mood = :happy => :happy > me.mood = :potato => :potato So you can extend classes at run-time any number of ways, this is just one of them. You can make it more magical with method_missing and a combination of instance_variable_get and instance_variable_set too: > module Magic > def method_missing(sym, *args) > name = sym.to_s > if name[-1,1] == '=' > instance_variable_set("@#{name[0, name.size - 1]}", *args) > else > instance_variable_get("@#{name}") > end > end > end => nil > class Person > include Magic > end => nil > p = Person.new > p.name = 'Alex' => 'Alex' > p.mood = :peppy => :peppy > puts p.name => Alex