From: Trans Date: 2005-04-17T22:59:39+09:00 Subject: Re: self Robert Klemme wrote: > Hey, that's an easy one: > > class Base > class << self > attr :state > end > instance_variable_set "@state", true > end > > class Derived < Base > end > > ?> Base.state > => true > >> Derived.state > => nil > > :-) > > State is never inherited. The reason why your code didn't do what you > wanted was that the implementation of the method was inherited. Ah, of course! --Until this thread I never really gave much thought to setting instance varaible in the class scope like this. Your simple example makes it quite plain. That'll be helpful, now that I see it clearly. Thank you. > Btw, I would find something like this useful in the std lib: > > class Class > def properties(*h) > h = h[0] if h.size == 1 > initial = {} > > h.each do |name, val| > attr_accessor name > initial[name]=val unless val.nil? > end > > unless initial.empty? > alias :new_plain :new > class< define_method(:new) do |*a| > obj = allocate > initial.each {|name, val| obj.send("#{name}=".to_sym, val)} > obj.instance_eval { initialize(*a) } > obj > end > end > end > > h > end > end > > >> class Foo > >> properties( :name => "foo", :age => 10 ) > >> end > => {:age=>10, :name=>"foo"} > >> Foo.new.name > => "foo" > >> class Bar > >> properties :name, :age > >> end > => [:name, :age] > >> Bar.new.name > => nil :-) Ara sent me something much like this recently, too. And something like them is in route to Ruby Carats for sure. Thanks for helpful code. T.