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
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.
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.
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.
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