SSP
SSP

Reputation: 2670

How can I access the class method and instance method in ruby?

By searching some blog and article I found that every class in Ruby is itself an instance of Class. What is the difference between class methods and instance methods and did ruby allow to create object of object?

I try to do something like this but still not able to understand

str = Class.new(String)
=> #<Class:0xb5be1418>

my_str = str.new()
=> ""

my_str = str.new("hello")
=> "hello"

my_str.class
=> #<Class:0xb5be1418>

str.class
=> Class

NOW FULLY CONFUSED so tell me about this

Upvotes: 6

Views: 945

Answers (2)

nkm
nkm

Reputation: 5914

class Dog
 # Returns the number of dog objects created using this class
 def self.count
 end

 # Returns name of the dog object
 def name
 end
end

From the above example, the generic method( which is related to all dog objects ) is called the class method.

Method that is related to a particular dog( dog object ) is called instance method.

According to ruby object models, Dog is a constant that points to an instance of class Class. Whenever a class method is added to Dog, a new class called Metaclass will be added in the class hierarchy to keep the class methods.

Upvotes: 0

Aliaksei Kliuchnikau
Aliaksei Kliuchnikau

Reputation: 13719

In the first sentence you create anonymous class with superclass of String:

my_str.class.superclass # => String

But this is not the essence of your actual question :)

Instance is an object of some class: String.new() # creates instance of class String. Instances have classes (String.new()).class #=> String. All classes are actually instances of a class Class: String.class # => Class. Instances of Class class also have superclass - class that they inherit from.

Instance method is a method that you can call on instance of an object.

"st ri ng".split # split is an instance method of String class

Class method in Ruby is a common term for instance methods of an object of Class class (any class).

String.try_convert("abc") # try_convert is a class method of String class.

You can read more about instance and class methods in this article.

Upvotes: 4

Related Questions