Own class in class

Hi

What is the [internal] difference between

class A
   def self.a end
end
class A1 < A
   def self.a1 end
end

         AND

class A
   class A1
      def self.a1 end
   end
end

···

----
Is it good style to nest classes? (or should a module with classes be used?)
How can I access A::A1.a1 ?

When do I use ::meth (instead of .meth) ?
---

Thanks!
Opti

Hi

What is the [internal] difference between

class A
  def self.a end
end
class A1 < A
  def self.a1 end
end

        AND

class A
  class A1
     def self.a1 end
  end
end

They're totally different.

In your first example, A1 is in the top-level namespace for Object
and inherits from A1. You can refer to it as "A1" in most of your
code:

  A1.a1

In your second example, there is no inheritance (from "A < A1"),
and you would need to use "A::A1" to access it outside of A,
since "A1" is in the "A" namespace.

Ignoring the inheritance difference; name resolution in Ruby is
much like a hierarchical filesystem (and also the common way to
organize files). If you use file-per-(class|module)
organization, the first example would be:

  $FOO/lib/a.rb
  $FOO/lib/a1.rb

And the second example:

  $FOO/lib/a.rb
  $FOO/lib/a/a1.rb

----
Is it good style to nest classes? (or should a module with classes be used?)

It depends on the situation. Sometimes it helps with
organization, sometimes it hurts.

I don't pay that much attention to how code is organized;
instead I care much more about how data flows through code.
In other words, I write code around the data it's supposed
to process, not the other way around.

How can I access A::A1.a1 ?

That only works in your second example.
You need to use "A1.a1" in your first example.

When do I use ::meth (instead of .meth) ?

They are equivalent when called by modules and class objects,
but "Foo.meth" is more common and easier-to-type on standard
keyboards than "Foo::meth"

···

Die Optimisten <inform@die-optimisten.net> wrote: