Class variables, instance variables, singleton; Ruby v. C++

Newb here coming from C++

Ok, I _think_ I know what a class variable is. It is similar to a
static variable in a class in C++. Rght?

An instance variable is apart of an instantiated class, right?

What's a singleton? I don't think it's the same as as singleton in
C++ parlance.

- - -

If Class X wants to access a class variable and/or constant in Class Y, must a class
method be defined or is there a direct way to do it?

Besides the Pickaxe book, can anyone recommend a document that
describes this a bit more clearly?

- - -

So I did a search for "ruby for c++ programmers." on Google and came
up with exactly one article
(http://californickation.blogspot.com/2008/02/first-look-at-ruby.html)
... one that says "Another funny fact is that searching for "Ruby for
Java programmers" retrieves a few articles right on the first page while "Ruby for C++ programmers" does not."

Anyone know of any articles?

Ralph Shnelvar wrote:

Newb here coming from C++

Ok, I _think_ I know what a class variable is. It is similar to a
static variable in a class in C++. Rght?

Yes.

An instance variable is apart of an instantiated class, right?

Not an "instantiated class", but a class instance -- which pretty much
describes everything in Ruby, since everything is an object.

What's a singleton? I don't think it's the same as as singleton in
C++ parlance.

But you are wrong.

- - -

If Class X wants to access a class variable and/or constant in Class Y,
must a class
method be defined

For variables, yes. Constants are directly accessible. Remember, Ruby
has no such thing as public data members in C++.

or is there a direct way to do it?

Only for constants (you know, the Class::CONSTANT syntax).

Besides the Pickaxe book, can anyone recommend a document that
describes this a bit more clearly?

The Pickaxe book explains all this *very* clearly.

- - -

So I did a search for "ruby for c++ programmers." on Google and came
up with exactly one article
(http://californickation.blogspot.com/2008/02/first-look-at-ruby.html\)
... one that says "Another funny fact is that searching for "Ruby for
Java programmers" retrieves a few articles right on the first page while
"Ruby for C++ programmers" does not."

Anyone know of any articles?

Do you really need something like that? And if you do, won't the Java
articles suffice?

Best,

···

--
Marnen Laibow-Koser
http://www.marnen.org
marnen@marnen.org
--
Posted via http://www.ruby-forum.com/\.

Newb here coming from C++

Ok, I _think_ I know what a class variable is. It is similar to a
static variable in a class in C++. Rght?

Yes.

A quick warning, though: Class variables behave weirdly with inheritance.
Avoid them. Since all Ruby classes are themselves objects, it makes more sense
to define an instance variable of the class.

That is, instead of doing this:

class Foo
  def bar
    @@some_count += 1
  end
end

Do this:

class Foo
  def self.increment_count
    @some_count += 1
  end
  def bar
    self.class.increment_count
  end
end

If you understand how that works, you should be able to understand this
example, which is how I'd actually do it:

class Foo
  class << self
    attr_accessor :some_count
  end
  def bar
    self.class.some_count += 1
  end
end

I'm sure there's a library somewhere that deals with these more easily.

An instance variable is apart of an instantiated class, right?

What's a singleton? I don't think it's the same as as singleton in
C++ parlance.

It probably is, but you never know...

There is actually a Singleton module in the standard library. The idea is to
prevent you from creating more than one instance of a given class.

There's also the idea of singleton methods -- for example, you can take two
objects of a given class, and define a method on one of them, without making a
new class. Try this in irb:

a = 'foo'
b = 'bar'
def a.speak
  puts self
end
a.class == b.class
a.speak
b.speak

This is, by the way, why we don't tend to care what class an object is, but
rather, how it behaves -- because in Ruby, duck typing is the only kind of
typing that makes sense, since you really can't know how an object will behave
just by looking at its class.

If Class X wants to access a class variable and/or constant in Class Y,
must a class method be defined or is there a direct way to do it?

Marnen is mostly right. There actually is a way -- class_variable_get -- but
that's cumbersome, and you shouldn't use it unless you know what you're doing.

And again, if you're already going to define a class variable, you might
consider using an instance variable on the class.

···

On Friday 27 November 2009 01:07:45 pm Ralph Shnelvar wrote:

Ralph Shnelvar wrote:

Newb here coming from C++

Ok, I _think_ I know what a class variable is. It is similar to a
static variable in a class in C++. Rght?

An instance variable is apart of an instantiated class, right?

What's a singleton? I don't think it's the same as as singleton in
C++ parlance.

- - -

If Class X wants to access a class variable and/or constant in Class Y,
must a class
method be defined or is there a direct way to do it?

Besides the Pickaxe book, can anyone recommend a document that
describes this a bit more clearly?

'The Ruby Programming Language' by Flanagan and Matsumoto describes the
differences between class variables and class instances variables. Don't
know if it will be any clearer than 'Programming Ruby' by Thomas,
Fowler, and Hunt.

···

- - -

So I did a search for "ruby for c++ programmers." on Google and came
up with exactly one article
(http://californickation.blogspot.com/2008/02/first-look-at-ruby.html\)
... one that says "Another funny fact is that searching for "Ruby for
Java programmers" retrieves a few articles right on the first page while
"Ruby for C++ programmers" does not."

Anyone know of any articles?

--
Posted via http://www.ruby-forum.com/\.

Newb here coming from C++

Ok, I _think_ I know what a class variable is. It is similar to a
static variable in a class in C++. Rght?

Yes.

A quick warning, though: Class variables behave weirdly with inheritance.
Avoid them. Since all Ruby classes are themselves objects, it makes more sense
to define an instance variable of the class.

That is, instead of doing this:

class Foo
  def bar
    @@some_count += 1
  end
end

Do this:

class Foo
  def self.increment_count
    @some_count += 1
  end
  def bar
    self.class.increment_count
  end
end

If you understand how that works, you should be able to understand this
example, which is how I'd actually do it:

I am clueless what all of the above does. It is WAY over my head.

I have read that section on how self is set in the Pickaxe book a
dozen times ... and I'm still lost.

How would I go about deciphering the meaning of what you wrote, above?

class Foo
  class << self
    attr_accessor :some_count
  end
  def bar
    self.class.some_count += 1
  end
end

And this is even more obscure to me.

···

On Friday 27 November 2009 01:07:45 pm Ralph Shnelvar wrote:

Hi --

···

On Sat, 28 Nov 2009, Steve Wilhelm wrote:

Ralph Shnelvar wrote:

Newb here coming from C++

Ok, I _think_ I know what a class variable is. It is similar to a
static variable in a class in C++. Rght?

An instance variable is apart of an instantiated class, right?

What's a singleton? I don't think it's the same as as singleton in
C++ parlance.

- - -

If Class X wants to access a class variable and/or constant in Class Y,
must a class
method be defined or is there a direct way to do it?

Besides the Pickaxe book, can anyone recommend a document that
describes this a bit more clearly?

'The Ruby Programming Language' by Flanagan and Matsumoto describes the
differences between class variables and class instances variables. Don't
know if it will be any clearer than 'Programming Ruby' by Thomas,
Fowler, and Hunt.

And of course this is one of the (many) problems with class variables:
they make obscure the otherwise rather simple notion that classes can
have instance variables because classes are objects and any object can
have instance variables.

David

--
THE COMPLEAT RUBYIST, Ruby training with Black/Brown/McAnally!
January 22-23, Tampa, Florida
Info and registration at http://www.thecompleatrubyist.com
--------------------------------------
My new job: http://tinyurl.com/yfpn9hz

Ralph Shnelvar wrote:
[...]

I am clueless what all of the above does. It is WAY over my head.

I have read that section on how self is set in the Pickaxe book a
dozen times ... and I'm still lost.

Then read it 13 times, or find supplementary material on the Web.
You've got to understand this stuff if you want to do nontrivial stuff
in Ruby.

How would I go about deciphering the meaning of what you wrote, above?

The same way you'd decipher anything else. Read it. Understand every
word and symbol. What you don't understand, look up. Ask questions
only after you've made a bona fide serious attempt to figure it out
yourself.

Best,

···

--
Marnen Laibow-Koser
http://www.marnen.org
marnen@marnen.org
--
Posted via http://www.ruby-forum.com/\.

I am clueless what all of the above does. It is WAY over my head.

I don't really know what to say, then, other than:

What is it you don't get?

I don't mean to be cruel, but there isn't a technical question in here -- not
really something that I can answer. Instead, all you have is this:

How would I go about deciphering the meaning of what you wrote, above?

Ask me, or ask the group. But ask something specific.

For example: Is it that you don't understand what I'm doing with 'def
self.whatever'? Or is it that you don't understand what self.class is? Or are
the words "Foo" and "bar" confusing? Maybe it was += that threw you off?

I could go through and attempt to explain every detail of how it works, and I
could probably do a good job, but it'd be a lot of effort on my part (better
spent writing a "how to program" book), and you'd probably find it pretty
condescending.

Also: Open up irb and mess around. See what happens. For example, type this
into your irb shell:

class Foo
  self
end

What does that return? Did you learn anything?

In other words: One very good way to learn is through experimentation. Run the
examples I've given and see what they do. Run them in a debugger, or sprinkle
a few 'puts' statements to see what's going on. Run them in irb, and play with
different versions of them.

···

On Friday 27 November 2009 05:00:32 pm Ralph Shnelvar wrote:

And of course this is one of the (many) problems with class variables:
they make obscure the otherwise rather simple notion that classes can
have instance variables because classes are objects and any object can
have instance variables.

David ... this may be the higher-level gestalt that I was missing. It
sure sounds like it.

Let me flesh out my questions/comments about this paragraph so that you and
others have something specific to answer. Let's call the classed F &
G.

(1) OK, classes are (i) objects; (ii) are executable code.

(2) If I do the following
      class F
      end
      f = F.new
      F.class # class
      f.class # F
this makes sense to me.

What (relevant and important conceptually) messages (other than "new")
can I send to a class? But see (3), below.

(3)
    class F
      def sub1
        @@x = 1
      end
    end

    class G
      self.sub1
        @@x=2
      end
    end

    # Why? Didn't the interpreter "see" @@x in class F?
    F.class_variables #

    # makes sense
    G.class_variables # ["@@x"]

    f = F.new

    # Why? Shouldn't the method inherit from the class?
    f.class_variables # undefined method

    f.sub1 # 1

    # makes sense. class variable now explicitly executed
    F.class_variables # ["@@x"]

    # How to use class_variable_get if the method is private???
    F.class_variable_get(:@@x) # error private method!

OK, that should do it for now.

I am clueless what all of the above does. It is WAY over my head.

I don't really know what to say, then, other than:

What is it you don't get?

I don't mean to be cruel, but there isn't a technical question in here -- not
really something that I can answer. Instead, all you have is this:

How would I go about deciphering the meaning of what you wrote, above?

Ask me, or ask the group. But ask something specific.

It is the gestalt ... the world-view ... that I am not getting. It is
not the specifics that are the difficulty.

For example: Is it that you don't understand what I'm doing with 'def
self.whatever'? Or is it that you don't understand what self.class is? Or are
the words "Foo" and "bar" confusing? Maybe it was += that threw you off?

I could go through and attempt to explain every detail of how it works, and I
could probably do a good job, but it'd be a lot of effort on my part (better
spent writing a "how to program" book), and you'd probably find it pretty
condescending.

Also: Open up irb and mess around. See what happens. For example, type this
into your irb shell:

class Foo
  self
end

What does that return? Did you learn anything?

In other words: One very good way to learn is through experimentation. Run the
examples I've given and see what they do. Run them in a debugger, or sprinkle
a few 'puts' statements to see what's going on. Run them in irb, and play with
different versions of them.

David, I thank you for trying to help.

There is a gestalt here that I am missing.

As the original poster, I said I'm coming from a C++ environment. I'm
actually pretty good there. Well, more than pretty good.

I've had SNOBOL, SPITBOL, and APL (several years) experience. I'm familiar with
interpreted code.

So ... there's something at a high level that is going on in your code that I'm unable to wrap
my head around.

···

On Friday 27 November 2009 05:00:32 pm Ralph Shnelvar wrote:

Ralph Shnelvar wrote:
[...]

Let me flesh out my questions/comments about this paragraph so that you
and
others have something specific to answer. Let's call the classed F &
G.

(1) OK, classes are (i) objects;

Right.

(ii) are executable code.

Wrong. Class *definitions* are executable code.

(2) If I do the following
      class F
      end
      f = F.new
      F.class # class
      f.class # F
this makes sense to me.

What (relevant and important conceptually) messages (other than "new")
can I send to a class?

See the documentation for class Class.

But see (3), below.

(3)
    class F
      def sub1
        @@x = 1
      end
    end

    class G
      self.sub1
        @@x=2
      end
    end

    # Why? Didn't the interpreter "see" @@x in class F?
    F.class_variables #

Probably not, since you haven't called the function yet!

    # makes sense
    G.class_variables # ["@@x"]

I'm actually rather surprised by this.

    f = F.new

    # Why? Shouldn't the method inherit from the class?
    f.class_variables # undefined method

No! class_variables is a class method of F. Instances do not get
access to their class' class methods, because they don't inherit from
the Class object in the conventional sense. The Class object is a
little bit like a JavaScript prototype, if that helps.

If it doesn't...well, I don't know what to say. If you're really as
good a C++ programmer as you claim to be, then you should be having no
trouble at all with the difference between class and instance methods.

    f.sub1 # 1

    # makes sense. class variable now explicitly executed
    F.class_variables # ["@@x"]

    # How to use class_variable_get if the method is private???
    F.class_variable_get(:@@x) # error private method!

Just don't. You're not meant to be getting at class variables from
outside the class. Use an accessor function if you need it.

(There is a way to call private methods from outside, but I will leave
you to find it out on your own. It's not generally a good thing, and
I'm not going to hand you a dangerous tool until you understand when not
to use it.)

OK, that should do it for now.

Best,

···

--
Marnen Laibow-Koser
http://www.marnen.org
marnen@marnen.org
--
Posted via http://www.ruby-forum.com/\.

I wouldn't say that classes are executable code. However the
difference between Ruby and C++ here is that in C++ a class is really
just a C Struct definition with new features like virtual member
functions and inheritance. It's a static compile time construct.

In Ruby on the other hand, classes are defined at run time as code is
executed, and the stuff inside a class definition is executable code.

Another related difference is that in C++ the class describes which
instance variables are present in every instance of that class by
virtue of the instance variables (members) being statically declared.

In Ruby an object gets instance variables one by one only when it
executes a method which sets the instance variable. Since classes are
objects this applies to classes as well.

A primary purpose of a class is to collect method implementations
which will be part of the repertoire of instances of that class.

So for example

class A
       # At this point the class has no class instance variables
      @class_instance_variable1 = 42 # This statement is executed when
the class def is, so
                                                      # after this A
has a class instance variable

     # The following defines a method which will be in the repertoire
of instances of A or any
     # of its subclasses
      def some_method
           @instance_var = "Hello"
      end

      # The self. makes the following a method of the class A. We
call this a class method
      # it will also be in the repertoire of any class objects which
subclass A (but not their instances)
      def self.a_class_method
           @class_instance_variable2 = [1, 2, 3]
      end
end

a = A.new
# At this point of execution:

···

On Sat, Nov 28, 2009 at 8:00 AM, Ralph Shnelvar <ralphs@dos32.com> wrote:

> And of course this is one of the (many) problems with class variables:
> they make obscure the otherwise rather simple notion that classes can
> have instance variables because classes are objects and any object can
> have instance variables.

David ... this may be the higher-level gestalt that I was missing. It
sure sounds like it.

Let me flesh out my questions/comments about this paragraph so that you and
others have something specific to answer. Let's call the classed F &
G.

(1) OK, classes are (i) objects; (ii) are executable code.

#
# The class A has ONE class instance variable @class_instance_variable1
#
# a, which is an instance of A, has NO instance variables

a.some_method

# And now a has an instance variable named @instance_var

A.a_class_method
# And now A has another class instance variable @class_instance_variable2

(2) If I do the following
class F
end
f = F.new
F.class # class
f.class # F
this makes sense to me.

What (relevant and important conceptually) messages (other than "new")
can I send to a class? But see (3), below.

Well like any object the answer to that depends on the class. All
classes are instances of Class, which defines three methods, only two
of which are normally called by user code.

Class#allocate which actually allocates the storage for a new
instance, this is rarely if ever overriden or called directly
Class#new which calls allocate to get a new instance and then calls
intialialize on the new instance passing any arguments along. This is
called often but rarely overridden.
Class#superclass which returns the superclass of the class, again
called but almost never overridden.

In addition Class is a subclass of Module, and inherits from module
the ability to collect methods and to serve as a nested namespace. So
every class object has the instance methods defined in Module as part
of its repertoire, I'll leave you to look these up.

And of course the instance methods defined in Object and the module
Kernel (which is included by Object) are part of the repertoire of
very Object and therefore every object which happens to be a class.

Some Ruby standard library classes like Array, Dir, File and others
define additional class methods specific to the class and its
subclasses.

(3)
class F
def sub1
@@x = 1
end
end

class G
self.sub1
@@x=2
end
end

# Why? Didn't the interpreter "see" @@x in class F?
F.class_variables #

See my explanation above. In this regard class variables like
instance variables

F doesn't have any class variables because the sub1 method hasn't been executed.

G does because you execute sub1 inside its class definition code. I
assume that you actually defined G as a subclass of F or you would
have gotten an undefined sub1 method error.

And you have invalid syntax in that snippet because there's an extra end

class G
    self.sub1
    @@x = 2
end # this ends the class def which consists of two
end

# makes sense
G.class_variables # ["@@x"]

f = F.new

# Why? Shouldn't the method inherit from the class?
f.class_variables # undefined method

Because f is an instance of F, and is not a class, class_variables is
a method defined in Module, not Object or kernel

f.sub1 # 1

# makes sense. class variable now explicitly executed
F.class_variables # ["@@x"]

# How to use class_variable_get if the method is private???
F.class_variable_get(:@@x) # error private method!

F.send(:class_variable_get, :@@x)

As others have pointed out class variables are a pretty wonky area of
Ruby. In Ruby 1.8 if G is a actually a subclass of F, then whether or
not @@x is the same instance variable for both depends in some cases
on whether or not F got its instance variable before G did or not.

When a class variable is initialized Ruby 1.8 looks through the chain
of superclasses to see if a class variable with that name already
exists, and if so uses that definition. If not it defines it for the
current class. Ruby 1.9 changed that so that now class variables are
no longer shared with subclasses.

Now it may seem hard or harsh, but I'd recommend that you try to
forget what you know about C++ when learning Ruby.

Although C++ and Ruby are both said to be object-oriented, they come
from two very different views of what that means. C++ is the epitome
of what Ralph Johnson calls the "Software Engineering" school, where
objects are seen as an extension of abstract data types. Ruby is of
what he calls the "Mystical" school where objects are seen as entities
which encapsulate both the data representation and the methods which
operate on the data, and which interact with other objects only by
message invocation of methods, looked up by name at runtime. Java is
influenced by the SE school, but is more dynamic in other regards.
Other mystical languages include Smalltalk, Self, and JavaScript
although JavaScript is not fundamentally OO.

--
Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

Hi --

> And of course this is one of the (many) problems with class variables:
> they make obscure the otherwise rather simple notion that classes can
> have instance variables because classes are objects and any object can
> have instance variables.

David ... this may be the higher-level gestalt that I was missing. It
sure sounds like it.

I have often made the observation that the answer to 75% of all
questions about Ruby is: "Because classes are also objects." :slight_smile:

Rick has explained most or all of what you were asking about. With
regard to class variables, I would encourage you to keep them somewhat
separate in your mind from the rest of the Ruby object and
variable/identifier model. Class variables are kind of layered on top,
as an expedient for getting class objects and their instances to share
data. Since classes are objects and their instances are *different*
objects, having them share data via variables is just a variation on
the theme of global variables; indeed, class variables are essentially
hierarchy-scoped globals.

Instance variables are a completely unrelated and totally different
matter: they are the mechanism for per-object state. Every object has
its own supply of instance variables, and by definition, no object can
see the instance variables of any other object -- even if object 1 is
a class and object 2 is an instance of that class. This is enforced
via the "self" mechanism: whenever you see an instance variable, you
are seeing an instance variable that belongs to self (whatever self is
at that moment).

I've always felt that it's unfortunate that class variables start with
"@@", because that conveys the impression that they're somehow akin to
instance variables. They're not; they're actually kind of the opposite
of instance variables, because they exist in order to blur the borders
between objects rather than to clarify them. They really should have
been "$$var" :slight_smile: Many of us would not mourn them if they disappeared
from Ruby.

David

···

On Sat, 28 Nov 2009, Ralph Shnelvar wrote:

--
THE COMPLEAT RUBYIST, Ruby training with Black/Brown/McAnally!
January 22-23, Tampa, Florida
Info and registration at http://www.thecompleatrubyist.com
--------------------------------------
My new job: http://tinyurl.com/yfpn9hz

(2) If I do the following
      class F
      end
      f = F.new
      F.class # class
      f.class # F
this makes sense to me.

What (relevant and important conceptually) messages (other than "new")
can I send to a class?

See the documentation for class Class.

But see (3), below.

(3)
    class F
      def sub1
        @@x = 1
      end
    end

    class G
      self.sub1
        @@x=2
      end
    end

    # Why? Didn't the interpreter "see" @@x in class F?
    F.class_variables #

Probably not, since you haven't called the function yet!

Didn't the interpreter parse it?

If I do
  class X
    def y
      xyzzy = 3++
    end
  end

then the interpreter/parser will complain immediately that there was a
syntax error even though the function method y was not executed.

    # makes sense
    G.class_variables # ["@@x"]

I'm actually rather surprised by this.

I made a mistake. I apologize.
  class G
    def self.sub1
      @@x=2
    end
  end

G.class_variables #

(I must have run the function accidentally. Sorry.)

    f = F.new

    # Why? Shouldn't the method inherit from the class?
    f.class_variables # undefined method

No! class_variables is a class method of F. Instances do not get
access to their class' class methods, because they don't inherit from
the Class object in the conventional sense. The Class object is a
little bit like a JavaScript prototype, if that helps.

If it doesn't...well, I don't know what to say. If you're really as
good a C++ programmer as you claim to be, then you should be having no
trouble at all with the difference between class and instance methods.

In C++, instances have access to the static variables and functions of
the class.

They don't inherit it ... but merely have access to it as if they
inherited it.

    f.sub1 # 1

    # makes sense. class variable now explicitly executed
    F.class_variables # ["@@x"]

    # How to use class_variable_get if the method is private???
    F.class_variable_get(:@@x) # error private method!

Just don't. You're not meant to be getting at class variables from
outside the class. Use an accessor function if you need it.

(There is a way to call private methods from outside, but I will leave
you to find it out on your own. It's not generally a good thing, and
I'm not going to hand you a dangerous tool until you understand when not
to use it.)

So ... when _can_ I use class_variable_get ???

Rick,

I know I am top-posting but ...

This has been super-helpful. It presents a helicopter view of what
was, uh, mystifying me. :slight_smile:

Many, many, thanks.

Ralph

Saturday, November 28, 2009, 7:46:26 AM, you wrote:

···

On Sat, Nov 28, 2009 at 8:00 AM, Ralph Shnelvar <ralphs@dos32.com> wrote:

> And of course this is one of the (many) problems with class variables:
> they make obscure the otherwise rather simple notion that classes can
> have instance variables because classes are objects and any object can
> have instance variables.

David ... this may be the higher-level gestalt that I was missing. It
sure sounds like it.

Let me flesh out my questions/comments about this paragraph so that you and
others have something specific to answer. Let's call the classed F &
G.

(1) OK, classes are (i) objects; (ii) are executable code.

I wouldn't say that classes are executable code. However the
difference between Ruby and C++ here is that in C++ a class is really
just a C Struct definition with new features like virtual member
functions and inheritance. It's a static compile time construct.

In Ruby on the other hand, classes are defined at run time as code is
executed, and the stuff inside a class definition is executable code.

Another related difference is that in C++ the class describes which
instance variables are present in every instance of that class by
virtue of the instance variables (members) being statically declared.

In Ruby an object gets instance variables one by one only when it
executes a method which sets the instance variable. Since classes are
objects this applies to classes as well.

A primary purpose of a class is to collect method implementations
which will be part of the repertoire of instances of that class.

So for example

class A
       # At this point the class has no class instance variables
      @class_instance_variable1 = 42 # This statement is executed when
the class def is, so
                                                      # after this A
has a class instance variable

     # The following defines a method which will be in the repertoire
of instances of A or any
     # of its subclasses
      def some_method
           @instance_var = "Hello"
      end

      # The self. makes the following a method of the class A. We
call this a class method
      # it will also be in the repertoire of any class objects which
subclass A (but not their instances)
      def self.a_class_method
           @class_instance_variable2 = [1, 2, 3]
      end
end

a = A.new
# At this point of execution:
#
# The class A has ONE class instance variable @class_instance_variable1
#
# a, which is an instance of A, has NO instance variables

a.some_method

# And now a has an instance variable named @instance_var

A.a_class_method
# And now A has another class instance variable @class_instance_variable2

(2) If I do the following
class F
end
f = F.new
F.class # class
f.class # F
this makes sense to me.

What (relevant and important conceptually) messages (other than "new")
can I send to a class? But see (3), below.

Well like any object the answer to that depends on the class. All
classes are instances of Class, which defines three methods, only two
of which are normally called by user code.

Class#allocate which actually allocates the storage for a new
instance, this is rarely if ever overriden or called directly
Class#new which calls allocate to get a new instance and then calls
intialialize on the new instance passing any arguments along. This is
called often but rarely overridden.
Class#superclass which returns the superclass of the class, again
called but almost never overridden.

In addition Class is a subclass of Module, and inherits from module
the ability to collect methods and to serve as a nested namespace. So
every class object has the instance methods defined in Module as part
of its repertoire, I'll leave you to look these up.

And of course the instance methods defined in Object and the module
Kernel (which is included by Object) are part of the repertoire of
very Object and therefore every object which happens to be a class.

Some Ruby standard library classes like Array, Dir, File and others
define additional class methods specific to the class and its
subclasses.

(3)
class F
def sub1
@@x = 1
end
end

class G
self.sub1
@@x=2
end
end

# Why? Didn't the interpreter "see" @@x in class F?
F.class_variables #

See my explanation above. In this regard class variables like
instance variables

F doesn't have any class variables because the sub1 method hasn't been executed.

G does because you execute sub1 inside its class definition code. I
assume that you actually defined G as a subclass of F or you would
have gotten an undefined sub1 method error.

And you have invalid syntax in that snippet because there's an extra end

class G
    self.sub1
    @@x = 2
end # this ends the class def which consists of two
end

# makes sense
G.class_variables # ["@@x"]

f = F.new

# Why? Shouldn't the method inherit from the class?
f.class_variables # undefined method

Because f is an instance of F, and is not a class, class_variables is
a method defined in Module, not Object or kernel

f.sub1 # 1

# makes sense. class variable now explicitly executed
F.class_variables # ["@@x"]

# How to use class_variable_get if the method is private???
F.class_variable_get(:@@x) # error private method!

F.send(:class_variable_get, :@@x)

As others have pointed out class variables are a pretty wonky area of
Ruby. In Ruby 1.8 if G is a actually a subclass of F, then whether or
not @@x is the same instance variable for both depends in some cases
on whether or not F got its instance variable before G did or not.

When a class variable is initialized Ruby 1.8 looks through the chain
of superclasses to see if a class variable with that name already
exists, and if so uses that definition. If not it defines it for the
current class. Ruby 1.9 changed that so that now class variables are
no longer shared with subclasses.

Now it may seem hard or harsh, but I'd recommend that you try to
forget what you know about C++ when learning Ruby.

Although C++ and Ruby are both said to be object-oriented, they come
from two very different views of what that means. C++ is the epitome
of what Ralph Johnson calls the "Software Engineering" school, where
objects are seen as an extension of abstract data types. Ruby is of
what he calls the "Mystical" school where objects are seen as entities
which encapsulate both the data representation and the methods which
operate on the data, and which interact with other objects only by
message invocation of methods, looked up by name at runtime. Java is
influenced by the SE school, but is more dynamic in other regards.
Other mystical languages include Smalltalk, Self, and JavaScript
although JavaScript is not fundamentally OO.

--
Best regards,
Ralph mailto:ralphs@dos32.com

Hi --

As others have pointed out class variables are a pretty wonky area of
Ruby. In Ruby 1.8 if G is a actually a subclass of F, then whether or
not @@x is the same instance variable for both depends in some cases
on whether or not F got its instance variable before G did or not.

When a class variable is initialized Ruby 1.8 looks through the chain
of superclasses to see if a class variable with that name already
exists, and if so uses that definition. If not it defines it for the
current class. Ruby 1.9 changed that so that now class variables are
no longer shared with subclasses.

I think that was true briefly but not more recently:

$ irb191
irb(main):001:0> class C
irb(main):002:1> @@x = 1
irb(main):003:1> end
=> 1
irb(main):004:0> class D < C
irb(main):005:1> @@x = 2
irb(main):006:1> end
=> 2
irb(main):007:0> class C
irb(main):008:1> @@x
irb(main):009:1> end
=> 2

(unless it's been re-reverted yet more recently and I haven't picked
up on it).

David

···

On Sat, 28 Nov 2009, Rick DeNatale wrote:

--
THE COMPLEAT RUBYIST, Ruby training with Black/Brown/McAnally!
January 22-23, Tampa, Florida
Info and registration at http://www.thecompleatrubyist.com
--------------------------------------
My new job: http://tinyurl.com/yfpn9hz

Many of us would not mourn them [@@ variables?] if they disappeared
from Ruby.

Do you mean to say there is a way around using class variables in
Ruby?

>> But see (3), below.
>>
>>
>>
>> (3)
>> class F
>> def sub1
>> @@x = 1
>> end
>> end
>>
>> class G
>> self.sub1
>> @@x=2
>> end
>> end
>>
>> # Why? Didn't the interpreter "see" @@x in class F?
>> F.class_variables #

> Probably not, since you haven't called the function yet!

Didn't the interpreter parse it?

If I do
  class X
    def y
      xyzzy = 3++
    end
  end

then the interpreter/parser will complain immediately that there was a
syntax error even though the function method y was not executed.

Yes, syntax errors are caught immediately by parsing. But think of instance
variables as a hash associated with the object and it might be more clear. For
example, if you did this:

SomeHash = {}
def foo
  SomeHash[:x] = :y
end

Would you expect SomeHash[:x] to exist just because you defined that method?

Now, I don't know whether instance variables are _actually_ implemented as a
hash. It might well be something much more efficient, but it behaves like a
hash, so that makes sense.

Also, consider: The method in question may _never_ be called. Why should Ruby
bother to create a variable that may never be used? That would be just as
foolish as implying that SomeHash[:x] exists before foo is called in my
example above. Sure, you could create it and set it to nil, but that'd be
pointless.

In C++, instances have access to the static variables and functions of
the class.

They don't inherit it ... but merely have access to it as if they
inherited it.

Instances indeed get access to class variables associated with that instance,
but again, class variables behave weirdly. But here's a quick example to help
clarify things:

SomeClass.new

Would you expect an object created that way to have a 'new' method of its own?
That is, would this make any sense:

SomeClass.new.new

Similarly, do the methods available at class creation time make any sense in
an object? For example, when creating a class:

class Foo
  attr_accessor :bar
end

You might think attr_accessor is a keyword. It isn't, it's just a method on
Class, so it's a class method on Foo.

There is no proper analog to "static functions" in C++, by the way -- they're
just methods on the class. But again, they aren't included into the instance
-- you access them on the class, just like you would with any other object.

So let me return to some simple examples that I hope make sense. Let's create
a counter for the number of instances that have been created.

class Foo
  def self.count
    @count
  end
  def self.increment_count
    @count ||= 0
    @count += 1
  end
end

This should be easy to understand. (If it's not, pretend I defined them
without self, and see if they make sense.)

Now, go define them, and play with them in irb. You wouldn't create any
instances of Foo yet, but you can do things like this:

Foo.count
Foo.increment_count
Foo.count
Foo.increment_count
Foo.increment_count
Foo.count

Go try that in irb, and see if the result makes sense.

Now let's move on. Keep the same class above, but add this -- if you're in the
same irb session, you can just re-open the class:

class Foo
  def initialize
    Foo.increment_count
  end
end

Now our counter should work as expected:

Foo.count
f = Foo.new
Foo.count

It won't tell you how many Foo objects actually exist. It's more a count of
how many have ever been created.

Also, if you understand this so far, go back to my earlier example that was
"way over your head" -- see if it makes sense. I'll give you an example -- if
you have a variable f, which is an instance of class Foo, what is f.class?

And if you're inside the initialize method of f, what is self? And what is
self.class?

> (There is a way to call private methods from outside, but I will leave
> you to find it out on your own. It's not generally a good thing, and
> I'm not going to hand you a dangerous tool until you understand when
not MLK> to use it.)

So ... when _can_ I use class_variable_get ???

You can use it whenever you want. When _should_ you use it?

Like instance_variable_get, it's designed for metaprogramming -- that is, when
you're trying to access a variable, but its name is dynamic.

I'll give you an example of when instance_variable_get might be used. Remember
attr_reader? (If not, look it up...) Now, for speed, attr_reader is defined
in C, but it can be defined in Ruby. Here's the obvious 'eval' solution:

class Module
  def attr_reader *names
    names.each do |name|
      eval "def #{name}; @#{name}; end"
    end
  end
end

But there are many reasons I dislike eval. Here's the solution I'd prefer:

class Module
  def attr_reader *names
    names.each do |name|
      var_name = :"@#{name}"
      define_method name do
        instance_variable_get var_name
      end
    end
  end
end

I don't expect you to follow every detail here. The use of define_method is an
advanced topic already. Hopefully, though, the fact that you already know how
to use attr_reader should give you an idea of how that works.

Also, I don't really expect you to need any of this yet -- attr_reader,
attr_writer, and attr_accessor should already do everything you need.

···

On Saturday 28 November 2009 08:43:30 am Ralph Shnelvar wrote:

Ralph Shnelvar wrote:

> Many of us would not mourn them [@@ variables?] if they disappeared
> from Ruby.

Do you mean to say there is a way around using class variables in
Ruby?

Yes, and it's been discussed in this thread. Go reread.

Best,

···

--
Marnen Laibow-Koser
http://www.marnen.org
marnen@marnen.org
--
Posted via http://www.ruby-forum.com/\.

Hi --

> Many of us would not mourn them [@@ variables?] if they disappeared
> from Ruby.

Do you mean to say there is a way around using class variables in
Ruby?

What people usually want to do when they reach for class variables is
maintain state on a class object. Class variables don't actually do
that. The way to maintain per-object state is with an instance
variable, optionally wrapped in accessor methods (mainly if you want
other objects to be able to read or write the object's state).

This is the so-called "class instance variable", which is really just
"an instance variable that happens to belong to a Class object". It's
common to use the phrase "class instance variable", but it's just a
way of clarifying what you mean. There's no separate "class instance
variable" language-level construct.

I would strongly recommend learning all about instance variables,
including the fact that, as objects, classes can have them; learn
about self, and how instance variables are resolved; and don't worry
about class variables for the moment. It's important to know they're
there, and how they work, but they don't shed much light on the
language overall.

David

···

On Mon, 30 Nov 2009, Ralph Shnelvar wrote:

--
THE COMPLEAT RUBYIST, Ruby training with Black/Brown/McAnally!
January 22-23, Tampa, Florida
Info and registration at http://www.thecompleatrubyist.com
--------------------------------------
My new job: http://tinyurl.com/yfpn9hz