Ruby class properties - ruby

The quiz problem:
Which of the following statements about classes in Ruby are true?
Array is an instance of Class.
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?

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.

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

2 is also correct. Self works like this in many languages.
http://ruby-doc.org/docs/keywords/1.9/Object.html

1, 2, and 3 are true. Array is an instance of Class, self is always the receiver, and Ruby does support multiple mixin inheritance. 4 is false, methods can be added, removed, and modified at any point in time.

Related

Ruby - in what module is `each` implemented in? [duplicate]

When sent a message, a Ruby object searches to see whether it has a method by that name to respond with. Its method lookup searches in the following order, and uses the first method it finds.
Singleton methods defined on itself (aka methods on its "eigenclass")
Methods defined in its class
Any modules mixed into its class, in reverse order of inclusion (only the earliest inclusion of a given module has any effect - if the superclass includes module A, and the subclass includes it again, it’s ignored in the subclass; if the subclass includes A then B then A, the second A is ignored) (update: note that this was written before Module.prepend existed)
Its parent class
Any methods mixed into the parent class, the parent's parent, etc.
Or, to put it more simply, it looks on itself, then everything in self.class.ancestors in the order they're listed.
This lookup path is followed at the moment the method is called; if you make an instance of a class, then reopen the class and add a method or mix one in via a module, the existing instance will gain access to that method.
If all of this fails, it looks to see if it has a method_missing method, or if its class does, its parent class, etc.
My question is this: aside from examining the code by hand, or using example methods like puts "I'm on module A!", can you tell where a given method came from? Can you, for example, list an object's methods and see "this one is on the parent class, this one is on module A, this one is on the class and overrides the parent class," etc?
Object#method returns a Method object giving meta-data about a given method. For example:
> [].method(:length).inspect
=> "#<Method: Array#length>"
> [].method(:max).inspect
=> "#<Method: Array(Enumerable)#max>"
In Ruby 1.8.7 and later, you can use Method#owner to determine the class or module that defined the method.
To get a list of all the methods with the name of the class or module where they are defined you could do something like the following:
obj.methods.collect {|m| "#{m} defined by #{obj.method(m).owner}"}
Get the appropriate Method (or UnboundMethod) object and ask for its owner. So you could do method(:puts).owner and get Kernel.
To find which instance methods are defined on A (but not on superclasses):
A.instance_methods(false)
To find which instance methods are defined on A AND its superclasses:
A.instance_methods
To find which class (or module) a given method is defined on:
method(:my_method).owner
To find which object is the receiver for a given method:
method(:my_method).receiver
You can use Object#method. For example,
[1, 2, 3].method(:each_cons) # => #<Method: Array(Enumerable)#each_cons>
tells that the each_cons method of an Array comes from the Enumerable module.

Why is EVERYTHING an instance of Class in Ruby? [duplicate]

This question already has answers here:
Ruby metaclass confusion
(4 answers)
Closed 7 years ago.
I don't quite get some things about the Ruby object model. First, is EVERYTHING in Ruby an instance of Class? These all produce true:
p Object.instance_of?(Class)
p Class.instance_of?(Class)
p Module.instance_of?(Class)
p BasicObject.instance_of?(Class)
class Hello; end
p Hello.instance_of?(Class)
I can't quite get how is it possible, if Object is a superclass of Class, how can it be both a superclass of Class and an instance of it at the same time (most diagrams on the Ruby Object Model clearly state this hierarchy)? Which allows for some crazyness like this:
p BasicObject.is_a?(Object) #=> true
where BasicObject.class is Class, and Class.is_a?(Object).
By the way, using Ruby 2.0.
First, is EVERYTHING in Ruby an instance of Class?
No, not everything is an instance of Class. Only classes are instances of Class.
There are lots of things which aren't instances of Class: strings, for example, are instances of String, not Class. Arrays are instances of Array, integers are instances of Integer, floats are instances of Float, true is an instance of TrueClass, false is an instance of FalseClass, nil is an instance of NilClass, and so on.
Every class is an instance of Class, just like every string is an instance of String.
if Object is a superclass of Class, how can it be both a superclass of Class and an instance of it at the same time (most diagrams on the Ruby Object Model clearly state this hierarchy)?
Magic.
Just like in most other languages, there are some core entities that are simply assumed to exist. They fall from the sky, materialize out of thin air, magically appear.
In Ruby, some of those magic things are:
Object doesn't have a superclass, but you cannot define a class with no superclass, the implicit direct superclass is always Object. [Note: there may be implementation-defined superclasses of Object, but eventually, there will be one which doesn't have a superclass.]
Object is an instance of Class, which is a subclass of Object (which means that indirectly Object is an instance of Object itself)
Class is a subclass of Module, which is an instance of Class
Class is an instance of Class
None of these things can be explained in Ruby.
BasicObject, Object, Module and Class all need to spring into existence at the same time because they have circular dependencies.
Just because this relationship cannot be expressed in Ruby code, doesn't mean the Ruby Language Specification can't say it has to be so. It's up to the implementor to figure out a way to do this. After all, the Ruby implementation has a level of access to the objects that you as a programmer don't have.
For example, the Ruby implementation could first create BasicObject, setting both its superclass pointer and its class pointer to null.
Then, it creates Object, setting its superclass pointer to BasicObject and its class pointer to null.
Next, it creates Module, setting its superclass pointer to Object and its class pointer to null.
Lastly, it creates Class, setting its superclass pointer to Module and its class pointer to null.
Now, we can overwrite BasicObject's, Object's, Module's, and Class's class pointer to point to Class, and we're done.
This is easy to do from outside the system, it just looks weird from the inside.
You should notice that:
p BasicObject.instance_of?(BasicObject)
prints false.
That is, the expression BasicObject is not an instance of BasicObject, it is an instance of something else, that is, it is a Class object, which represents an object that holds (for example) the class methods, such as new.
For example:
p (BasicObject.new()).instance_of?(BasicObject)
prints true, and
p (BasicObject.new()).instance_of?(Class)
prints false.
All of your examples were by definition classes. Classes are also objects. But what you didn't do was look at an instance of a class:
p Object.new.class
p Hello.new.class
Classes define the form of an object, and by definition, a class is a Class. But when you instantiate class into an object, the object is the new type. But you can still see that the object's class is itself Class:
p Hello.new.class.class

Initialization Order of Ruby class Class and class Module [duplicate]

I understand that all classes in ruby are instances of metaclass Class. And that "regular" objects are instances of these classes (the instances of metaclass Class).
But I keep wondering, I mean classes are root of objects, classes are themselves instances of Class (called metaclass because its instances are classes). I saw in some blogs some overriding of method new, of class Class.
So Class behaves as a class, but its instances are classes. So it seems we have a circle, it looks likes class Class is an instance of itself.
I'm clearly missing a point here. What is the origin of class Class?
Here's an example that's confusing me:
class Class
def new
#something
end
end
But keyword class implies an instance of class Class. So how do this work?
how do this work
Easy: it doesn't. Not in Ruby, anyway.
Just like in most other languages, there are some core entities that are simply assumed to exist. They fall from the sky, materialize out of thin air, magically appear.
In Ruby, some of those magic things are:
Object doesn't have a superclass, but you cannot define a class with no superclass, the implicit direct superclass is always Object. [Note: there may be implementation-defined superclasses of Object, but eventually, there will be one which doesn't have a superclass.]
Object is an instance of Class, which is a subclass of Object (which means that indirectly Object is an instance of Object itself)
Class is a subclass of Module, which is an instance of Class
Class is an instance of Class
None of these things can be explained in Ruby.
BasicObject, Object, Module and Class all need to spring into existence at the same time because they have circular dependencies.
Just because this relationship cannot be expressed in Ruby code, doesn't mean the Ruby Language Specification can't say it has to be so. It's up to the implementor to figure out a way to do this. After all, the Ruby implementation has a level of access to the objects that you as a programmer don't have.
For example, the Ruby implementation could first create BasicObject, setting both its superclass pointer and its class pointer to null.
Then, it creates Object, setting its superclass pointer to BasicObject and its class pointer to null.
Next, it creates Module, setting its superclass pointer to Object and its class pointer to null.
Lastly, it creates Class, setting its superclass pointer to Module and its class pointer to null.
Now, we can overwrite BasicObject's, Object's, Module's, and Class's class pointer to point to Class, and we're done.
This is easy to do from outside the system, it just looks weird from the inside.
Once they do exist, however, it is perfectly possible to implement most of their behavior in plain Ruby. You only need very barebones versions of those classes, thanks to Ruby's open classes, you can add any missing functionality at a later time.
In your example, the class Class is not creating a new class named Class, it is reopening the existing class Class, which was given to us by the runtime environment.
So, it is perfectly possible to explain the default behavior of Class#new in plain Ruby:
class Class
def new(*args, &block)
obj = allocate # another magic thing that cannot be explained in Ruby
obj.initialize(*args, &block)
return obj
end
end
[Note: actually, initialize is private, so you need to use obj.send(:initialize, *args, &block) to circumvent the access restriction.]
BTW: Class#allocate is another one of those magic things. It allocates a new empty object in Ruby's object space, which is something that cannot be done in Ruby. So, Class#allocate is something that has to be provided by the runtime system as well.
There is a meta-circularity given by the "twist" link. It is the built-in superclass link from the root's eigenclass to the Class class. This can be expressed by
BasicObject.singleton_class.superclass == Class
A clue to understanding the .class map is seeing this map as derived from the eigenclass and superclass links: for an object x, x.class is the first class in the superclass chain of x's eigenclass. This can be expressed by
x.class == x.eigenclass.superclass(n)
where eigenclass is a "conceptual alias" of singleton_class
(resistant to issues with immediate values), y.superclass(i) means i-th superclass of y and n is smallest such that x.eigenclass.superclass(n) is a class. Equivalently, eigenclasses in the superclass chain of x.eigenclass are skipped (see rb_class_real which also reveals that in MRI, even superclass links are implemented indirectly – they arise by skipping "iclasses").
This results in that the class of every class (as well as of every eigenclass) is constantly the Class class.
A picture is provided by this diagram.
The metaclass confusion has 2 main sources:
Smalltalk. The Smalltalk-80 object model contains conceptual inconsistencies that are rectified by the Ruby object model. In addition, Smalltalk literature uses dialectics in terminology, which unfortunately has not been sufficiently remedied in the Ruby literature.
The definition of metaclass. At present, the definition states that metaclasses are classes of classes. However, for so called "implicit metaclasses" (the case of Ruby and Smalltalk-80) a much more fitting definition would be that of meta-objects of classes.
Yes, Class is an instance of itself. It's a subclass of Module, which is also an instance of class, and Module is a subclass of Object, which is also an instance of Class. It is indeed quite circular — but this is part of the core language, not something in a library. The Ruby runtime itself doesn't have the same limits thast you or I do when we're writing Ruby code.
I've never heard the word "metaclass" used to talk about Class, though. It isn't used much in Ruby at all, but when it is, it's usually a synonym for what's officially called a "singleton class of an object," which is an even more confusing topic than Object-Module-Class triangle.
Though it is a little out of date, this article by _why may help in understanding the behavior. You can find an even deeper dive into the subject in Paolo Perrotta's Metaprogramming Ruby.

Singleton methods in ruby

I understand that singleton methods live in singleton classes (or eigenclasses). My first question is:
Why can't they live inside objects? I know that in ruby, an object can
only hold instance variables. But I cannot see why singleton methods
weren't designed to be in objects.
Next,
If objects can only contain instance variables, how come classes,
which are objects of Class, are able to store methods?
I am just confused at conceptual level. I have read many times that ruby object model is consistent.
Ad 1, they indeed do live inside an object. Singleton class, in fact, is just a mental construct. 'Singleton' here means, that, by definition, the class has only one instance - that object. So the identity of the object and the singleton class is intextricably the same.
Ad 2, the answer is, because Matz decided so. More precisely, not classes, but modules (Module class) store methods, and Class < Module.
It might be of interest to you, that a singleton class of an object is not instantiated by default. Until you try to access it, it simply does not exist. This is because if all the singleton classes were immediately instantiated, you would have an infinite chain of singleton classes:
o = Object.new
o.singleton_class
o.singleton_class.singleton_class
o.singleton_class.singleton_class.singleton_class
...
The goal of singleton pattern is to ensure, that only one object of a particular class will live within a system.
So the methods still live in a class, but you just can't create another instance of that class.
A class is an object, but because it serves as a template for other objects, its own instances, it keeps their instance methods inside its module. But if you treat a class as an ordinary object, for example call #object_id on it, it gives you all the behavior expected of normal objects.
Continuing from our discussion in comments: Strictly speaking, the ability to store methods (and constants) is a buit-in special ability of modules (Module class). Class class happens to be a subclass of Module class, which makes it inherit modules' ability to store methods, but you are free to create other objects (not just classes) with that ability:
class MyPetObjectThatCanStoreMethods < Module
def greet; puts "Bow, wow!" end
end
Fred = MyPetObjectThatCanStoreMethods.new
So, Fred is not exactly a module, but decsends from Module and has thus ability to store methods and constants:
module Fred # this is allowed!
LENGTH = 19
def rise; puts "I'm rising!" end
end
You can't do this with normal objects, only with module descendants!
Fred::LENGTH #=> 19
Fred.greet
#=> Bow, wow!
Fred.rise
#=> NoMethodError
That's because Fred stores #rise method, just like modules do, but unlike #greet method, #rise is not its instance method! To gain access to it, we will have to include Fred in a suitable class:
o = Object.new
o.rise
#=> NoMethodError
class << o # Including Fred in the metaclass of o
include Fred
end
o.rise
#=> I'm rising!
If objects can only contain instance variables, how come classes, which are objects of Class, are able to store methods?
class Foo
def suprim;end
end
Foo.instance_methods(true).grep(/^sup/)
#=> [:suprim]
I searched for Class's instance method superclass ,but didn't appear,as Foo is an instance of Class,so it should not store the
instance methods of Class. But yes,Foo returns only the methods of its instances to be used. Which is natural.Look below now:
Class.instance_methods(true).grep(/^sup/)
#=>[:superclass]

Is singleton class of an object already created?

I would like to know is there any ways to check is singleton class of an
object already created?
ex: obj.singleton_class_defined?
The singleton class of an object is always defined. In 1.8.7 you can use singleton_methods to see if an object already has associated singleton methods:
>> foo = ''
=> ""
>> foo.singleton_methods
=> []
1.9.2 (possibly also earlier 1.9s, I can't remember) also has a method called singleton_class, which saves you from doing the class << self; self ; end thing we all got used to:
>> foo.singleton_class #=> #<Class:#<String:0x00000100ba5648>>
Edit:
Since you tagged this with "object-model", I also wanted to recommend the following link:
http://www.hokstad.com/ruby-object-model.html
To quote from there:
A meta-class is for all practical
purposes an actual class. It is an
object of type Class. The only thing
"special" about a meta-class is that
it is created as needed and inserted
in the inheritance chain before the
objects "real" class. So inside the
MRI interpreter object->klass can
refer to a meta-class, that has a
pointer named "super" that refers to
the next class in the chain. When you
call object.class in MRI, the
interpreter actually "skips" over the
meta-class (and modules) if it's
there.

Resources