Prasad Surase
Prasad Surase

Reputation: 6574

ruby object model + class creation based on another class

my question may be very basic n foolish but i m confused why the output is this way.

MyClass = Class.new String
MyClass.ancestors
=> [MyClass, String, ..]

AnotherClass = Class.new MyClass
=> AnotherClass 
AnotherClass.ancestors
=> [AnotherClass, MyClass, String, ..]

in the above code, i m creating a new instance of Class named MyClass and have passed the object(everything in ruby is an object) 'String' as the parameter. Why does 'String' occur in the ancestors list for MyClass. I haven't inherited MyClass from String but that's what ruby seems to be doing. It does work as copy constructor but why the inheritance?

Upvotes: 0

Views: 65

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369556

I haven't inherited MyClass from String

Yes you have. That's what the argument to Class::new means:

new(super_class=Object)a_class

Creates a new anonymous (unnamed) class with the given superclass (or Object if no parameter is given).

Upvotes: 1

Jiří Pospíšil
Jiří Pospíšil

Reputation: 14412

The following

class A < B
end

is in fact just a syntax sugar for

A = Class.new B

See Random Ruby Tricks: Class.new and the official docs for more info.

Upvotes: 3

Related Questions