The quiz problem:
Which of the following statements about classes in Ruby are true?
Array
is an instance ofClass
.- When
self
is used within the definition of an instance method, it refers to the current instance of the class.- Ruby supports multiple inheritance.
- Public methods of a class cannot be redefined after an instance of that class is instantiated.
More than one answer could be correct.
I know that (3) is incorrect because Ruby does not support multiple inheritance. I chose (1) but got the question wrong. Are other statements about the classes in Ruby also true?
#1 and #2 are both correct answers. You already know that Ruby doesn't support multiple inheritance, although it does support module mixins. So, 3 and 4 are false, while 1 and 2 are true; see below for details.
First of all, Array is a class, but doesn't inherit from Class or have Class in its ancestry. Consider:
Array.is_a? Class
# => true
Array.ancestors
# => [Array, Enumerable, Object, PP::ObjectMixin, Kernel, BasicObject]
Array < Class
# => nil
On the other hand, as @Priti correctly points out in his comment below, Array is an instance of Class:
Array.instance_of? Class
# => true
So, while Array doesn't inherit from Class in its ancestry chain, it is (strictly speaking) an instance of a Class. That makes #1 technically correct.
The self method is actually a bit more complex than one might expect. Ruby 1.9 defines it this way:
self is the "current object" and the default receiver of messages (method calls) for which no explicit receiver is specified. Which object plays the role of self depends on the context.
- In a method, the object on which the method was called is self
- In a class or module definition (but outside of any method definition contained therein), self is the class or module object being defined.
- In a code block associated with a call to class_eval (aka module_eval), self is the class (or module) on which the method was called.
- In a block associated with a call to instance_eval or instance_exec, self is the object on which the method was called.
So, #2 is correct, but only tells part of the story.
Ruby supports open classes (see Classes are Open), so you can redefine instance and class methods at run-time. So, #4 is wrong.
While all other answers are explaining each options,but I think Array is an instance of Class. is true.Object#instance_of? says: Returns true if obj is an instance of the given class. See also Object#kind_of?.
Array.instance_of? Class # => true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With