Ruby class methods and instance methods

Source: Internet
Author: User

A class method is also called a static method. It is called by class name. Instance method. You must create a new instance before using it.

 
Class Foo def self. bar puts 'class method' end def Baz puts 'instance method' endendfoo. bar # class method # Foo. baz # error: Undefined method 'baz' For foo: Class (nomethoderror) Foo. new. baz # instance method # Foo. new. bar # error: Undefined method 'bar' for # <0x2d61a1c> (nomethoderror)

  

In this example, bar is the class method, and how it is defined: def self. Bar, self is the point to the current class. The instance method is simple: def Baz.

A flexible scripting language like Ruby is rare. It provides a variety of methods for defining class methods.

 # way 1 class Foo def self. bar puts 'class method' endendfoo. bar # "class method" # way 2 class Foo class 

the first and third methods are not described in detail. The use of self is equivalent to the use of JavaScript this. The second has the meaning of self-inheritance. It is very elegant to write less self when we add multiple class methods.

let's look at the instance method. There are also several solutions:

 # way 1 class Foo def Baz puts 'instance Method1 'endendfoo. new. baz # "instance Method1" puts '-------------' # way 2 class Foo attr_accessor: bazendfoo = Foo. newfoo. baz = 'instance method2 'puts Foo. baz # "instance method2" puts '-------------' # way 3 class Foo; endfoo = Foo. newdef Foo. lazy puts 'instance method3 'endfoo. Lazy # "instance method3" 

the first is a direct definition, the second is the attr_accessor syntax, and the third is the late binding, this method is only valid for that instance.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.