Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class vs Class.new, module vs Module.new

Tags:

ruby

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

I know that:

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

  2. When we want to inherit, we can pass an argument: Class.new(ancestor). When we don't specify an ancestor, it is set to the Object. class use this syntax: class A < Ancestor

  3. Class.new returns an object. class A returns nil. Same goes for modules.

Did I miss something?

like image 376
Darek Nędza Avatar asked Dec 20 '13 09:12

Darek Nędza


2 Answers

The interesting point that you missed between class keyword and Class::new is - Class::new accepts block. So when you will be creating a class object using Class::new you can also access to the surrounding variables. Because block is closure. But this is not possible, when you will be creating a class using the keyword class. Because class creates a brand new scope which has no knowledge about the outside world. Let me give you some examples.

Here I am creating a class using keyword class :

count = 2

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

Here one using Class.new :

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

The same difference goes with keyword module and Module::new.

like image 69
Arup Rakshit Avatar answered Sep 27 '22 15:09

Arup Rakshit


Class.new returns an object. class A returns nil. Same goes for modules.

That's wrong. A class/module definition returns the value of the last expression evaluated inside of the class/module body:

class Foo
  42
end
# => 42

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

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

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

like image 44
Jörg W Mittag Avatar answered Sep 27 '22 15:09

Jörg W Mittag