Reputation: 350
I can create a class using a constant name with class
keyword:
class MyClass1; end
I can also create a class with Class.new
and assign that to a constant or a variable:
MyClass2 = Class.new do; end
myClass3 = Class.new do; end
but I cannot create a class using class
keyword with a name that begins in lowercase:
class myclass4; end # => Error
Is there a fundamental difference between these four? Isn't myclass3
a regular class?
Upvotes: 0
Views: 86
Reputation: 168091
Similar to Andrew Marshall's answer, but also different.
Think of it this way:
The class Foo ...
syntax does more than defining a class; in addition to defining a class, it necessarily names it when called for the first time, and a class name must be a constant. Note that, in principle, a class can be nameless (see #3).
On the other hand, assignment can be done to a variable or a constant. There is no restriction to that.
A purer way to create a class is to use Class.new
. Using this syntax, you do not have to name it. So it is okay to assign it to a variable:
foo = Class.new
# => #<Class:0x007f36b23159a8>
Only when it is assigned to a constant for the first time does it get named:
Foo = foo
# => Foo
Upvotes: 1
Reputation: 96934
The first method (class MyClass; end
) is an explicit part of the language syntax (in that class
is a keyword), and the class’s name must be a constant.
The second method (Class.new
) is just a normal method call, and returns an anonymous instance of Class. This anonymous instance can then be treated like any other object.
Other than that, there are no differences between the two methods. Note that you can still assign the first type into a non-constant, but it must also first be assigned into a constant:
class MyClass; end
my_class = MyClass
Upvotes: 1