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.
Related
Today I came across the Pathname class in Ruby and noticed that you could directly call the class itself as a method (which would basically return a new instance):
Pathname("some/path")
# => #<Pathname:some/path>
I've been trying to replicate the same thing with my CustomClass but haven't been successful. I don't know what these methods are called and I can't find any Ruby code that gives me an idea on how to do this. My Question is how do I use the Class name as method?
Things I've tried so far:
Defining self.self()
Defining self.class()
Using the class << self syntax
Googling - But it just returns comparisons of class methods vs instance methods
This isn't using the class itself. This is calling a method in Kernel with the same name as the class. It's generally discouraged to do it yourself as you pollute almost all objects with new methods and leads to confusion (as you already see).
Here is the documentation for the method. There are a few others like Array, Hash, String, etc.
What you're looking for is a conversion method to coerce the input to the instance of the class.
It is not a method of the class itself, but a method in Kernel module. So in order to be able to use the form of MyClass(value) you should add the method to Kernel module:
module Kernel
def Foo(value)
# you can implement any logic here
value.is_a?(Foo) ? value : Foo.new(value)
end
module_function :Foo
end
class Foo
def initialize(bar)
#bar = bar
end
end
baz = Foo('bar')
#=> #<Foo:0x007fd4e5070370 #bar="bar">
Foo(baz)
#=> #<Foo:0x007fd4e5070370 #bar="bar">
baz == Foo(baz)
#=> true
This is not a class call, but a shortcut. And the trickiest part - it was defined for a Kernel module to be available everywhere in the form as you just specified.
Please proceed to the link of the official docs. There you can see, that requiring a Pathname module, it extend Kernel module to add the method of the same name.
To be honest, I strongly recommend against extending Kernel with your own method. Or at least to use refinements
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.
I m trying to understand the Ruby Object Model. I understood that the instance methods are saved in the class rather than in the objects of the class because it removes redundancy. I read that whenever a class is created, a metaclass is created too for the newly created class. the metaclass stores the class methods. ie the singleton methods of the class are located in the metaclass. eg
class MyClass
def hi
'hi object'
end
def self.bye
'bye singleton method'
end
end
for the above MyClass, a metaclass (say #MyClass) is created too. now the method 'hi' is an instance level method and can be called on all the objects of MyClass. method 'bye' is a singleton method of MyClass and it resides in the #MyClass. the reason (i think so) why 'hi' is saved in MyClass rather than all the objects of MyClass is because it avoids redundancy. But we cant have more than one classes named MyClass. So why not store 'bye' in MyClass rather than in #MyClass, since we cant have more than one MyClass. I have absolutely no idea why this is the way it is and i m just trying to understand the reason behind it.
-----UPDATE----
metaclass store the class information like the singleton methods and other stuff. But since a class is a singleton object(its an instance of class Class and is alone of its type) then why not save all the information in the class itself rather than the metaclass.
Just to be super duper clear.
Here is a quick ruby script that explains the question:
#!/usr/bin/env ruby
puts ObjectSpace.count_objects[:T_CLASS] #>> 471
class X
def self.foo
end
def bar
end
end
puts ObjectSpace.count_objects[:T_CLASS] #>> 473
This is what the OP meant by "ObjectSpace.count_objects[:T_CLASS] increments the count by 2." Let's call the extra class the singleton class of X, because that appears to be what Ruby calls it internally.
irb> X
=> X
irb> X.singleton_class
=> <Class: X>
Notice that the #foo method is an instance method of X.singleton_class, not X.
irb> X.instance_methods(false)
=> [:baz]
irb> X.singleton_class.instance_methods(false)
=> [:foo]
So why is :foo stored in X.singleton_class instead of X? Isn't there only ever going to be one X?
I believe the main reason is for consistency. Consider the following, simpler scenario concerning plain instance objects.
car = Car.new
def car.go_forth_and_conquer
end
As #mikej explained superbly, this new method is stored in car's singleton class.
irb> car.singleton_class.instance_methods(false)
=> [:go_forth_and_conquer]
Classes are Objects
Now, classes are objects too. Each class is an instance of Class. Thus, when a class (say, X) is defined, ruby is really creating an instance of Class, and then adding methods to the instance (similar to what we did to car above.) For example, here is an alternative way to create a new class
Car = Class.new do
def go_forth_and_conquer
puts "vroom"
end
end
Car.new.go_forth_and_conquer
Therefore, it is much easier to just reuse the code and do it the same way (i.e. keep foo in X.singleton_class.) This probably requires less effort and will lead to fewer surprises, so no one will ever need to write code to handle Class instances differently from other instances.
Probably Doesn't Matter
You might be thinking that if Ruby did not have singleton classes for instances of Class, there could be some memory savings. However, it sounds to me that where bar is actually stored is an implementation detail that we probably shouldn't count on. Rubinius, MRI, and JRuby could all store methods and instances differently, as long as the behavior is consistent. For all we know, there could be a reasonable implementation of Ruby that doesn't eagerly create singleton classes for class objects, for the exact same reasons you outlined, as long as the overall behavior conforms to the ruby spec. (E.g. an actual singleton class doesn't exist until the #singleton_class method is first invoked.)
This isn't quite an answer to your question, but it might be useful. Two things to think about that might help:
metaclass is not really a good name for what's going on here when you think of how the meta prefix is used in other scenarios. eigenclass which you will see used in other documentation is probably a better name, meaning "an object's own class"
It's not just classes that have an eigenclass, every object does
The eigenclass is used to store methods that are specific to a particular object. e.g. we can add a method to a single String object:
my_string = 'Example'
def my_string.example_method
puts "Just an example"
end
This method can only be called on my_string and not on any other String object. We can see that it is stored in my_string's eigenclass:
eigenclass = class << my_string; self; end # get hold of my_string's eigenclass
eigenclass.instance_methods(false) # => [:example_method]
Remembering that classes are objects, in this context, it makes sense that the methods specific to a particular class should be stored in that class's eigenclass.
Update: actually, there is an eigenclass for the eigenclass. We can see this more easily if we add eigenclass as a method to Object:
class Object
def eigenclass
class << self
self
end
end
end
and then we can do:
irb(main):049:0> my_string.eigenclass
=> #<Class:#<String:0x269ec98>>
irb(main):050:0> my_string.eigenclass.eigenclass
=> #<Class:#<Class:#<String:0x269ec98>>>
irb(main):051:0> my_string.eigenclass.eigenclass.eigenclass # etc!
=> #<Class:#<Class:#<Class:#<String:0x269ec98>>>>
whilst this seemingly creates an infinite regress, this is avoided because Ruby only creates the eigenclasses on as they are needed. I think the name "metaclass" really is a source of part your confusion because you are expecting a "metaclass" to hold some kind of information that it actually doesn't.
The reason really boils down to what self is. For any given method, self is an instance of the object that the method is defined one.
In an instance method, stored on MyClass, self will be the instance of MyClass that you called #hi from. In a class method, self will be the instance of the metaclass (that is, the class itself). Doing it with the metaclass means that the concept of self is unchanged, even when operating on a class, which is itself just a singleton instance of its metaclass.
As per The Ruby Programming Language the class methods, are infact singleton methods on an instance of the class that got same name as the class.
Class Foo
def self.bar
"Am a class method"
end
end
here method self.bar can be depicted as a singleton method on an instance Foo of type Class Foo.
#the following code is just to explain on what actually are class methods called
Foo.bar #=> "Am a class method"
#the call is done on an instance of class Foo which got ref name Foo
We can go on adding more class/singleton/metaclass methods on Foo by
class<<Foo
def self.another_bar
"Am another class method"
end
end
Foo.another_bar #=>"Am another class method"
More formally singleton methods are defined as instance methods of an anonymous eigenclass/meta class.
Though conceptually wrong we can assume classes are objects in this context, so as to have a better grasp.
This concept is there to bring in true Object Oriented - ness in all levels of the language. Objective-C implements class methods in a similar fashion.
In Obj-C metaclasses bails out as classes which contain information about the classes it meta. And the principles of inheritance do apply for meta-classes as well, there super class is its classe's superclasse's metaclass and climbs up so until it reaches the base object, whoe's metaclass is the metaclass itself. More reading on this can be done here.
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]
I'm reading 'metaprogramming in ruby'
its such an EXCELLENT book. Seriously, it talks about stuff that I never hear mentioned elsewhere.
I have a few specific questions however about objects (I'm in the first few chapters)
I understand that the RubyGems gem installs the method 'gem' to the module Kernel so that it shows up on every object. Is there a reason they didnt put it into the Object class?
He talks about how when ruby looks for the method it always goes right then up. What exactly does 'up' mean? I see it in the diagram, its just that I dont really understand the purpose of 'up'. he doesnt explain that part much.
What is the point of the Object class? How come those methods cant be just placed into Class? If every object belongs to a class (even if its Class), then what is the point of object, basicobject, and kernel?
String, Array, blah blah are obviously an instance of Class. Class is also an instance of itself. So if Class is an instance of Class.... how does it also inherit from Object? Where in the code does it relates to BOTH Class and Object?
I know kernel contains methods such as puts that can be used everywhere, and this relates to question 1, but why cant they just condense it and put it all into Object... where it would seem everything inherits from object anyway
Both would work, but typically methods on Object should only be methods that deal with a particular object. Puting things in the Kernel module are less about about object and more global.
I assume it means "up the inheritance chain". So it looks for the method on the child class, then on that classes parent class until it finds one or runs out of parent classes.
Object is the base class of all objects, naturally (For ruby 1.8 at least). The crazy part is that a class is actually an instance of the Class class. (you follow that?) So adding instance methods to Class would add methods to class objects, but not instances of those classes.
Nearly everything in ruby is an object. Class.superclass is actually Module (which is like a class you can't instantiate) and Module.superclass returns Object. So Class < Module < Object is the inheritance chain if the Class class. (For ruby 1.8 at least)
More convention than anything. Since Object can get rather HUGE, it's customary to put things into modules and then combine those modules later. If the method doesn't deal with an instance of an object directly as self then the method doesn't belong directly in Object. More global non-object instance methods like gem go in the Kernel module to signify that they are simply methods available everywhere.
Some more about class objects and inheritance...
class Foo < Bar
def hi
puts 'Hi!'
end
end
What this does is really quite awesome. It defines a class object, of course. Now this class object is configured to have a name Foo, a parent class Bar and a method hi. This info is sort of like this class object's meta data.
Now the class object Foo itself is an instance of Class. But Foo defines a class that inherits from Bar. The Class class defines a data structure to store this meta data about a class.
You can think of the Class class sorta kinda being defined like this:
class Class < Module
# fictional method called on class creation
def set_meta_data(name, superclass, methods)
#name = name
#superclass = superclass
#methods = methods
end
# fictional way in which an instance might be created
def new
instance = Object.new
instance.superclass = #superclass
instance.addMethods(#methods)
instance
end
end
So a class object itself would inherit from Class but it would create objects that do not.
Thinking of classes as objects can be a bit mind bending in this way, but this also why ruby is awesome.
For 1 and 5, pseudo-keyword commands tend to go into Kernel rather than Object.
For 2, it makes sense for sub-classes to be "down" relative to their parent class (sub literally meaning "beneath"). Therefore if you're heading for a parent class and its ancestors, you have to go "up".
For 3, an object object is not an instance of Class, it is an instance of Object.
For 4, what's wrong with something being an instance of Class and inheriting from Object? All classes inherit from Object.