Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby class properties

Tags:

class

ruby

The quiz problem:

Which of the following statements about classes in Ruby are true?

  1. Array is an instance of Class.
  2. When self is used within the definition of an instance method, it refers to the current instance of the class.
  3. Ruby supports multiple inheritance.
  4. 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?

like image 383
user86408 Avatar asked Dec 12 '22 13:12

user86408


2 Answers

TL;DR

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

Array.is_a? Class

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.

Object#self

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.

Open Classes

Ruby supports open classes (see Classes are Open), so you can redefine instance and class methods at run-time. So, #4 is wrong.

like image 68
Todd A. Jacobs Avatar answered Dec 28 '22 16:12

Todd A. Jacobs


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
like image 40
Arup Rakshit Avatar answered Dec 28 '22 16:12

Arup Rakshit