How is it that this works? When the following is run "hi from class"
is printed twice. What is going on inside ruby to make this behave like this? Am I NOT in fact making an instance method for class
class Class
def foo
puts "hi from class"
end
end
Class.foo
x = Class.new
x.foo
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class. Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference.
Instance method are methods which require an object of its class to be created before it can be called. To invoke a instance method, we have to create an Object of the class in which the method is defined.
Class method can access and modify the class state. Static Method cannot access or modify the class state. The class method takes the class as parameter to know about the state of that class. Static methods do not know about class state.
I don't know whether you're aware of that, but when you do class Class ... end
, you're not creating a new class named Class
, you're reopening the existing class Class
.
Since Class
is the class that all classes are instances of that means that Class
is an instance of itself. And because of that you can call any instance methods of Class
directly on Class
the same way you can on any other class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With