Reputation:
Class.new.new
# => #<#<Class:0x44f3a2>:0xd7244e>
I am curious to know what is created. Is it an object of object? Any technical explanation will be appreciated.
Upvotes: 3
Views: 97
Reputation: 76240
With Class.new
you are creating a new class. In fact not only you can create classes via the common syntax:
class Bird
def is
"word"
end
end
but you can also use Class::new
like this:
Bird = Class.new do
def is
"word"
end
end
In the above example you can run Bird.new.is
and it will return "word"
just like in the first example.
It is useful to create anonymous classes or classes that you can rename at your will.
In your case:
Class.new.new
By simply calling Class.new
you are creating a new anonymous class with no custom methods or instance variables which is then later instantiated via the second new
method.
Upvotes: 6
Reputation: 34774
You can follow it through in the console:
irb(main):011:0> c = Class.new
=> #<Class:0x000000028245e0>
c
is a new class.
irb(main):012:0> c.new
=> #<#<Class:0x000000028245e0>:0x0000000282a170>
Calling c.new
returns you a new instance of the new class you just created.
Upvotes: 3
Reputation: 65435
my_class = Class.new # makes a new class which is a subclass of Object
my_instance = my_class.new # makes a new instance object of the class
Upvotes: 0
Reputation: 51151
Class.new
creates and returns Class
instance (which is class). If you call on it new
again, previously created class will be instantiated.
Upvotes: 1