Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 920
SSP Avatar asked Feb 09 '12 12:02

SSP


People also ask

Can instance methods access class methods?

Instance methods can access class variables and class methods directly. This means a method that doesn't have a static modifier i.e. an instance method can access a static variable or call a method with the static modifier.

How do I access instance methods?

To invoke a instance method, we have to create an Object of the class in which the method is defined. public void geek(String name) { // code to be executed.... } // Return type can be int, float String or user defined data type.


1 Answers

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.

like image 171
Aliaksei Kliuchnikau Avatar answered Sep 24 '22 05:09

Aliaksei Kliuchnikau