On 3/1/07, james.d.masters / gmail.com <james.d.masters / gmail.com> wrote:
> On Mar 1, 11:35 am, Gary Wright <gwtm... / mac.com> wrote:
> > ...
> > I think you are asking for something which is quite easy:
> >
> > class A
> >    class <<self
> >      attr_accessor :per_class
> >    end
> > end
> > ...
>
> Yes, this is kind of what I'm referring to; however, my gripe is that
> this is somewhat esoteric.  The beauty of other parts of Ruby is that
> the code is terse and readable.

Go back and look at my earlier post.

Just what does @var mean?

In a method it means that this is an instance variable of the object
executing the method.

rick@frodo:/public/rubyscripts$ cat civ.rb
class C

  def instance_var
    @instance_var
  end

  def instance_var=(val)
    @instance_var = val
  end

  def C.class_instance_var
    @class_instance_var
  end

  def C.class_instance_var=(val)
    @class_instance_var = val
  end
end

class D < C
end

c = C.new
c1 = C.new

c.instance_var = 'c'
c1.instance_var = 'c1'

puts "c.instance_var=#{c.instance_var}"
puts "c1.instance_var=#{c1.instance_var}"

C.class_instance_var="C"
puts "C.class_instance_var=#{C.class_instance_var}"
puts "D.class_instance_var=#{D.class_instance_var}"
D.class_instance_var="D"
puts "C.class_instance_var=#{C.class_instance_var}"
puts "D.class_instance_var=#{D.class_instance_var}"
rick@frodo:/public/rubyscripts$ ruby civ.rb
c.instance_var=c
c1.instance_var=c1
C.class_instance_var=C
D.class_instance_var=
C.class_instance_var=C
D.class_instance_var=D
rick@frodo:/public/rubyscripts$

All a class instance variable is, is an instance variable of the
class. so @class_inst_var is a class instance variable of C because
it's in class methods of C.

Gary's example looks a bit esoteric perhaps, but the attr_accessor
method is just a metamethod which generates the two methods for each
of my variables.  My code could be replaced with the equivalent:

class C

  attr_accessor :instance_var

  class << C  # or class << self
    attr_accessor :class_instance_var
  end

end

class D < C
end

The class<<self (within the definition of C) or class << C (which
could also be outside) simply puts us in a context where self is the
class C, which allows us to invoke the private method attr_accessor.

To put this in the context of another older OO language, Smalltalk has
instance variables, class instance variables and class variables, but
unlike in ruby the existance of these has to be declared, with
something like

Object subclass: #C
    instanceVariables: 'instanceVariable'
    classInstanceVariables: 'classInstanceVariable'
    classVariables: 'ClassVariable'

The difference between Ruby and Smalltalk springs from Matz' decision
to use sigils* to differentiate between the variable types rather than
requiring declaration.

* http://en.wikipedia.org/wiki/Sigil_%28computer_programming%29

-- 
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/