Class vs Class.new, module vs Module.new

What is the difference between class and Class.new and module and Module.new ?

I know that:

  • Class.new / Module.new create an anonymous class / module . When we assign it a constant for the first time, it becomes the name of this class / module . class / module do this automatically.

  • When we want to inherit, we can pass an argument: Class.new(ancestor) . When we do not specify an ancestor, it is set to Object . class use this syntax: class A < Ancestor

  • Class.new returns an Object . class A returns nil . The same goes for module s.

Did I miss something?

+6
source share
2 answers

An interesting point that you missed between the class and Class::new keywords is that Class::new takes a block. Therefore, when you create a class object using Class::new , you can also access the surrounding variables. Because the block is closing. But this is not possible when you will create a class using the class keyword. Because class creates a completely new area that does not know about the outside world. Let me give you some examples.

Here I create a class using the class keyword:

 count = 2 class Foo puts count end # undefined local variable or method `count' for Foo:Class (NameError) 

This uses Class.new :

 count = 2 Foo = Class.new do |c| puts count end # >> 2 

The same thing happens with the module and Module::new keywords.

+8
source

Class.new returns object . class A returns nil . The same goes for module s.

It is not right. A class / module definition returns the value of the last expression evaluated inside the class / module body:

 class Foo 42 end # => 42 

Typically, the last expression evaluated inside the body of the class / module will be the expression of the method definition, which in current versions of Ruby returns Symbol representing the name of the method:

 class Foo def bar; end end # => :bar 

In older versions of Ruby, the return value of the method definition expression was determined by the implementation. Rubinius returned a CompiledMethod object for the method in question, while YARV and most others simply returned nil .

+1
source

All Articles