0

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks. now i get why Object is the default superclass. i thought it might be setting some internal pointer in the cpp code but this is set in Class.new. thanks again.
1

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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.