11 views
What's the output of the following Ruby 3 code?
class Example; end example = Example.new example.instance_of?(Object) # => ???
The correct answer is
true
false
nil
Object
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
In this quiz, we are looking at a piece of code that involves Ruby classes and instance checking. Let's break it down to understand why it behaves the way it does:
class Example; end example = Example.new example.instance_of?(Object) # => false
The given code defines a simple class named Example
, and then creates an instance of this class, assigning it to the variable example
.
The line p example.instance_of?(Object)
is what we need to analyze to determine the output.
The method instance_of?
checks if an object is an instance of a specific class, and only that class.
It does not consider inheritance. In this case, we are checking if example
is an instance of Object
.
While it is true that every class in Ruby ultimately inherits from Object
, the instance_of?
method only returns true
if the object is directly an instance of the given class.
Since example
is an instance of Example
, not directly Object
, the expression example.instance_of?(Object)
will return false
.
To clarify further, consider the difference between instance_of?
and kind_of?
.
The instance_of?
method checks if the object is an instance of the exact class specified, without considering inheritance.
In our case, example.instance_of?(Object)
returns false
because example
is an instance of Example
.
On the other hand, the kind_of?
method checks if the object is an instance of the specified class or one of its ancestors.
If we were to use example.kind_of?(Object)
, it would return true
because Example
inherits from Object
, and example
is therefore indirectly an instance of Object
.
The distinction is subtle but important: instance_of?
is strict and only matches the exact class, while kind_of?
is more flexible and considers the inheritance chain.
Subscribe to RubyCademy and get free access to all our courses, plus hundreds of fun Ruby cards, quizzes, guides, and tutorials!
RubyCademy ©