I defined methods specific_data1 and specific_data2 in meta class, and expected these methods belong to the singleton class:
class User
def User.specific_data1
"user specific data defined on user"
end
class << self
def specific_data2
"user specific data defined in meta class"
end
end
end
But neither of the methods is found in:
User.singleton_class.methods
Please help me understand what singleton_method on User class is and how it is useful.
Object#methods returns the methods of that object. Methods defined in a class aren't methods of that class object, they are methods of that class's instances.
This has nothing to do with singleton classes, it's true for all classes:
class Foo
def bar; end
end
Foo.methods.include?(:bar)
# => false
Foo.new.methods.include?(:bar)
# => true
Foo.instance_methods
# => [:bar]
Here's how that works with your example:
User.methods.grep(/specific/)
# => [:specific_data1, :specific_data2]
User.singleton_methods
# => [:specific_data1, :specific_data2]
User.singleton_class.instance_methods.grep(/specific/)
# => [:specific_data1, :specific_data2]
Both of the methods you defined are defined as instance methods on the singleton_class.
User.singleton_class.instance_methods(false)
# => [:specific_data1, :specific_data2]
Jorg got the technical part of your question right. You want to check
User.singleton_class.instance_methods
As for this
Please help me understand what singleton_method on User class is and how it is useful."
Suppose you have an object x and you want to define a method for it. One way would be to define the method in x's class, but this has the side effect of defining the method for all other objects of that class! What if you just want to define the method for the single object x?
Ruby solves this problem by letting you create a class which has only a single instance: x. This is the singleton class. Methods defined in it will only affect x because the singleton class is a subclass of x.class and its only instance is x. Singleton methods are just regular methods defined in a singleton class.
Related
From Wikibooks' Ruby Programming/Overview:
When I said that every Ruby object has a class, I lied. The truth is, every object has two classes: a “regular” class and a singleton class. An object’s singleton class is a nameless class whose only instance is that object. Every object has its very own singleton class, created automatically along with the object. Singleton classes inherit from their object’s regular class and are initially empty, but you can open them up and add methods to them, which can then be called on the lone object belonging to them. This is Ruby’s secret trick to avoid “class methods” and keep its type system simple and elegant
The above passage says that Ruby's secret trick to avoid class methods. I don't understand what the author means here. Where is Ruby stopping us to avoid class methods? for an example, look at the example shown below
class Raj
def self.hi
puts 'Hi'
end
def hello
puts 'hello'
end
end
object=Raj.new
object.hello
Raj.hi
As you can see in the preceding example, the class methods can still be created.
yes?
I understand that there are no true class methods in Ruby; instead, they are methods that are created for the Raj object.
But, in any case, it's allowing me to create the method 'hi,' right?
So, what does it mean when it says, 'This is Ruby's secret trick for avoiding "class methods" and keeping its type system simple and elegant'?
I understand that there are no true class methods in Ruby; instead, they are methods that are created for the Raj object.
That's exactly it, though.
def self.hi
puts 'Hi'
end
This is not a class method or static method. Those don't exist in Ruby. That's the whole point. Your class Raj defines an object of type Class. We can see its type with the #class function.
> Raj.class
=> Class
We can also see its ancestors.
> Raj.class.ancestors
=> [Class, Module, Object, PP::ObjectMixin, Kernel, BasicObject]
Class inherits from Module, since (for the most part) classes can do everything modules can. Module, in turn, inherits from Object, which has some modules of its own mixed in (PP:ObjectMixin is for pretty-printing, and Kernel gets you the nice helpers like puts) and eventually inherits from the root class BasicObject.
But this isn't the whole story, for Raj has its own class as well: its singleton class. We can see the full story by calling #singleton_class instead of #class.
> Raj.singleton_class.ancestors
=>
[#<Class:Raj>,
#<Class:Object>,
#<Class:BasicObject>,
Class,
Module,
Object,
PP::ObjectMixin,
Kernel,
BasicObject]
Now there's a lot more going on. Raj is an instance of the singleton class of Raj, which inherits from the singleton class of Object, which in turn inherits from the singleton class of BasicObject, which inherits from Class and all of the stuff we saw before.
So when you define a method on the class Raj, you're defining it (as an instance method) on the singleton class #<Class:Raj>. And that class (currently) has one instance: Raj.
By the way, it's also useful to know that the term "singleton class" is a bit of a lie. As you can see, the class is very much not a singleton in general. For instance, the singleton class of Object, called #<Class:Object> above, actually has several instances: Object, Raj, String, and most Ruby classes. Personally, I prefer to call them eigenclasses for that reason, but "singleton class" is the official (and more well-known) term.
The author is talking about the singleton class in this sentence, there is a really nice article to deep dive into ruby singleton class: https://medium.com/#leo_hetsch/demystifying-singleton-classes-in-ruby-caf3fa4c9d91
Here is a nice example extracted from this article:
class Vehicle
def initialize(kms)
#kms = kms
end
def drive
puts "let's go!"
end
end
car = Vehicle.new(1000)
bus = Vehicle.new(3000)
def car.drive
print "I'm driving a car! "
super
end
car.drive # "I'm driving a car! let's go!"
bus.drive # "let's go!"
As you can see, here the #drive method has been overridden but only for the car object, the bus object is still using the #drive method defined in the Vehicle class.
This new method is defined on the singleton class (or shadow class) of the object, this is allowing you to define new methods on the fly on an object without polluting all the objects of this class.
This means that Ruby doesn't implement class methods.
Indeed, the Ruby OBJECT Model, allows you to "emulate" the definition of class methods by defining instance methods on the Eigenclass:
class Greeting
def self.hello
'hello world!'
end
def self.eigenclass
class << self
self
end
end
end
Greeting.eigenclass # => #<Class:Greeting>
Greeting.eigenclass.name # => nil
Greeting.singleton_methods # => [:hello, :eigenclass]
Greeting.eigenclass.instance_methods(false) # => [:hello, :eigenclass]
First, we define a Greeting.eigenclass method. This method returns self in the context of the eigenclass — by using the class << self ... end syntax. In this case, self contains an unnamed instance of the class Class (a.k.a an anonymous class). This anonymous class keeps track of the class to which it is attached — the Greeting class in our case.
Then, we can see that the singleton methods of the Greeting class are the instance methods of the Greeting eigenclass.
Feel free to have a look to this very detailed article to learn more about this concept.
To illustrate #Sébastien P.'s answer:
dice = [1,2,3,4,5,6] #an ordinary array instance
def dice.throw #now it has an extra
sample
end
p dice.throw #=>3
I'm near the finish of the Ruby track in Code Academy, and I'm curious about a peculiar thing: I was under the impression that a class is a repository of constants, methods, etc... and that in order to access most of them, you would first need to create an instance of that class or in some cases the methods of themselves can be invoked (as in they are all technically part of the global object). And then I saw something like this:
#Worked
Time.now
I understood as this as the method [now] of instance of class [Time] being invoked. I then tried to invoke the method on its own:
#Failed
now
and that failed, and I assumed that while a method can be created in the general scope [as part of the global object], if it relies on initialized variables of "parent" class, it cannot be called on its own, because it would not know which object to search for those initialized variables. Following that I created a test class:
class Clock
def initialize
#hours = 1
#minutes = 30
end
def showTime
puts "The time is: #{#hours}:#{#minutes}"
end
end
#this worked
watch = Clock.new
watch.showTime
#this failed
showTime
I then just created a basic method (assuming it's in the global level)
def mymethod
puts "The mighty METHOD!"
end
#Works
mymethod
and calling this method the way I did, without referencing the global object worked. So... the questions I have are as follows:
How can [Time.now] be called in this fashion? Shouldn't there be an instance of Time first created?
Why can't I call the method [now] on its own? Am I right that it relies on resources that it cannot find when called this way?
Why could I not call the method showTime on its own? But if I define any method on the "global" level I can access it without referencing the global object
First of all, your intuition is correct.
Every methods must be an instance method of some receiver.
Global methods are defined as private instance methods on Object class and hence seem to be globally available. Why? From any context Object is always in the class hierarchy of self and hence private methods on Object are always callable without receiver.
def fuuuuuuuuuuun
end
Object.private_methods.include?(:fuuuuuuuuuuun)
# => true
Class methods are defined as instance methods on the "singleton class" of their class instance. Every object in Ruby has two classes, a "singleton class" with instance methods just for that one single object and a "normal class" with method for all objects of that class. Classes are no different, they are objects of the Class class and may have singleton methods.
class A
class << self # the singleton class
def example
end
end
end
A.singleton_class.instance_methods.include?(:example)
# => true
Alternative ways of defining class methods are
class A
def self.example
end
end
# or
def A.example
end
Fun fact, you can define singleton methods on any object (not just on class objects) using the same syntax def (receiver).(method name) as follows
str = "hello"
def str.square_size
size * size
end
str.square_size
# => 25
"any other string".square_size
# => raises NoMethodError
Some programming language history — Singleton classes are taken from the Smalltalk language where they are called "metaclasses". Basically all object-oriented features in Ruby (as well as the functional-style enumerators on Enumerable) are taken from the Smalltalk language. Smalltalk was an early class-based object-oriented language created in the 70ies. It was also the language that invented graphical user interfaces like overlapping windows and menus et cetera. If you love Ruby maybe also take a look at Smalltalk, you might fall in love yet again.
This is known as a class method. If CodeAcademy didn't cover it, that's a shame. Here's some examples:
# basic way
class Foo
def self.bar; :ok; end
end
Foo.bar # => :ok
# alternate syntax
class Foo
class << self
def bar; :ok; end
end
end
# alternate syntax, if Foo class already exists
def Foo.bar; :ok; end
# alternate approach if Foo class already exists
Foo.class_exec do
def bar; :ok; end
end
# to define a class method on an anonymous 'class' for a single instance
# you won't need to use this often
Foo.new.singleton_class.class_exec do
def bar; :ok; end
end
# to define a class method on an instance's actual class
Foo.new.class.class_exec do
def bar; :ok; end
end
Another way to get class methods is to extend a module.
module FooMethods
def bar; :ok; end
end
module Foo
extend FooMethods
end
Foo.bar # => :ok
Note that with Modules, the methods are always defined as instance methods. This way they can be either extended into class scope or included into instance scope. Modules can also have class methods, using the exact same syntax / examples as shown above with classes. However there's not such as easy to load a module's class methods via include or extend.
How can [Time.now] be called in this fashion? Shouldn't there be an
instance of Time first created?
The Time.now method is a class method, not an instance method and therefore can be called directly on the Time class rather than an instance of it Time.new
Class methods are defined on the class themselves using the self keyword:
class Time
def self.now
# code
end
end
Time.now # works
Why can't I call the method [now] on its own? Am I right that it
relies on resources that it cannot find when called this way?
When you call a method "on its own" you're actually implicitly calling it on self:
self.now
The above is the same as just doing:
now
Why could I not call the method showTime on its own? But if I define
any method on the "global" level I can access it without referencing
the global object
You defined the showTime method on a specific class so you have to send that method to that class. When you define a method in the "global" scope you're implicitly defining it on self and the subsequent call to mymethod is actually self.mymethod so it will work.
Time.now is a class method.
To define a class method, you need to define the method with self. : def self.method_name
class Clock
#hours = 1
#minutes = 30
def self.showTime
puts "The time is: #{#hours}:#{#minutes}"
end
end
Clock.showTime
#=> The time is: 1:30
If you want to call now on its own, you can do so inside Time class :
class Time
puts now
#=> 2017-01-19 22:17:29 +0100
end
Given a self as below, how to find its class name:
self = #<Class:#<PaymentRequestx::PaymentRequest:0x0000000b2a3400>>
What I am looking for is to return PaymentRequestx::PaymentRequest. self.name (nil) and self.class.name (Class) do not return the right answer. Here is more info about the self:
How can I retrieve PaymentRequestx::PaymentRequest?
If you want to get the only instance of a singleton class, you can find it in ObjectSpace.
some_singleton_class = some_obj.singleton_class
some_obj_2 = ObjectSpace.each_object(some_singleton_class).first
some_obj_2.object_id == some_obj.object_id #=> true
If your self is a class's singleton class, then the class you're searching for is the only instance of that singleton class.
ObjectSpace.each_object(self).first.name #=> should return "PaymentRequestx::PaymentRequest"
This approach may not be fast so avoid using it whenever possible.
WARNING: If the class you want has subclasses, then this approach will not work. For example
ObjectSpace.each_object(Object.singleton_class).to_a
will return a huge amount of classes (think why).
UPDATE
You can do further filter from the search result from ObjectSpace.
def instance_of(singleton_class)
ObjectSpace.each_object(singleton_class).find do |obj|
obj.singleton_class == singleton_class
end
end
instance_of(Object.singleton_class) #=> Object
Inspection of the form:
#<Class:#<SomeModule>>
indicates the singleton class of SomeModule. When SomeModule is actually an anonymous instance of a module, it looks like this:
a = Module.new
# => #<Module:0x007f6f86eb8fa0>
a.singleton_class
# => #<Class:#<Module:0x007f6f86eb8fa0>>
You have an anonymous class that is the singleton class of an anonymous instance 0x0000000b2a3400 of PaymentRequestx::PaymentRequest, which must be a module. You cannot name a singleton class, so you cannot get its name.
On getting the original module of a singleton class, follow an answer provided here.
Try self.ancestors.first.name
:ancestors returns a list of modules prepended or included to whatever it's called on.
I've just got deeper in Ruby hierarchy to understand it. For example,
class Test
end
t = Test.new
So, if I want to get class of t I need to get 'class' property:
t.class # 'Test'
If I want to get parent of Test class I should use 'superclass' method:
t.class.superclass # BasicObject
But also Test is an instance of Class class. So, if I execute the following thing:
t.class.class # Class
So, I don't understand the difference between 'superclass' and 'class.class'; why aren't Class superclass for Test? What does it mean? Doest Test inherit methods of Class or BasicObject or both ones? Please, explain this thigns to me. I came from Java and I didn't hear about this features before. Thanks.
First of all, by default, implicit superclass of the class you define is Object, not BasicObject.
Now, Test.superclass methods returns class that Test directly inherits from. While Test.class returns class that Test is instance of. Remember that classes in Ruby are also objects, all objects in Ruby belongs to some class.
Every object responds to class. It says what class the object is an instance of.
Only classes respond to superclass. It says what class the class is a subclass of.
Foo = Class.new # class Foo; end
foo = Foo.new
Foo.class # Class
foo.class # Foo
Bar = Class.new(Foo) # class Bar < Foo; end
Bar.class # Class
Bar.superclass # Foo
All classes are instances of Class. Ruby does not allow subclasses of Class.
All objects are descendents of class Object. Class is object too and it is an instance of Object, which can seem a little weird.
class Test
end
Test.class # => Class
Test.superclass # => Object
Object.class # => Class
Class.superclass # => Module
Module.class # => Class
Module.superclass # => Object
Object.superclass # => BasicObject
All descendents of class Object inherit quite a lot of methods like clone, dup, freeze and many many other methods. On the other hand BasicObject will provide you almost no methods - it doesn't even provide you methods: methods and public_methods.
Object , Class, Module , NilClass are all instances of Class.
1) First Doubt how can something be an instance of itself ? (i.e 'Class' is an instance of 'Class') or is my assumption wrong ?
2) If Object , Class ,Module etc ... are all objects then how can they have class methods ? Because class methods can only be called from classes and are not present in objects. (or is my assertion incorrect that Object, Class , Module are all objects ?)
3)If Object , Class , Module are not objects then what are they ?
3) Does a class method account for the missing method in instance a of Class and ultimately a decrease in method count ?
>> Class.methods.count
=> 82
>> a = Class.new
=> #<Class:0x1005519b8>
>> a.methods.count
=> 81
Class objects are indeed objects.
Class methods are actually methods defined in the class's eigenclass (singleton class). That is why those methods are not available to actual instances of said classes.
Here's a way to help you see this: first, add a singleton_class method if you don't already have it:
module Kernel
def singleton_class
class << self
self
end
end
end
Now, try the following:
String.instance_methods
String.singleton_class.instance_methods
Class.instance_methods
Class.singleton_class.instance_methods
c = Class.new
c.instance_methods
c.singleton_class.instance_methods
This will help you gain an appreciation for what methods are available to instances of a class, versus what methods are methods on the class (i.e., instances of the class's singleton class).
(You can pass a false argument to each of those instance_methods calls to see which methods are defined for that class, and not any superclasses.)
The Ruby core is composed by Class, Object, Module and Kernel. They're predefined, so the Class class can be an instance of itself.
They have class methods because they're classes, too (and classes are objects).
I can't answer it yet. I have to discover which method is missing to think in an answer.