Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class Class - instance vs. class methods

Tags:

ruby

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
like image 504
slindsey3000 Avatar asked Oct 03 '11 18:10

slindsey3000


People also ask

What is difference between a method and an instance?

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.

What is the difference between a class method and an instance method in Java?

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.

What is method and instance?

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.

What is the difference between Classmethod and Staticmethod?

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.


1 Answers

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.

like image 124
sepp2k Avatar answered Oct 01 '22 02:10

sepp2k