Class methods and class extensions in Ruby object-oriented programming, ruby Object-Oriented Programming

Source: Internet
Author: User

Ruby object-oriented programming methods and class extensions, ruby object-oriented programming

Class method

The essence of a class method is a single-piece method that lives in a single-piece class of that class. There are three definition methods, namely:

# Law one
def MyClass.a_class_method; end


# Law two
class MyClass
  def self.anther_class_method; end
end


# Law three *
class MyClass
  class << self
    def yet_another_class_method; end
  end
end

Among them, the third method is revealed, the essence of the class method, especially remember!

Class extension

Class extensions define class methods by adding modules to the single-piece class of the class.

module MyModule
  def my_method; ‘hello '; end
end

class MyClass
  class <self
    include MyModule
  end
end

MyClass.my_method

The above code shows the implementation of the concrete class extension. A MyModule module is introduced into the single-class class of the MyClass class, because the my_method method is an instance method of the single-class class of MyClass.

Object extension

Class methods are special cases of single-piece methods, so you can apply the technique of class extension to any object. This technique is object extension
 
# Method one: open a single class to expand
module MyModule
  def my_method; ‘hello '; end
end

obj = Object.new
class << obj
  include MyModule
end

obj.my_method # => “hello”
obj.singleton_methods # => [: my_method]
# Method two: Object # extend method
module MyModule
  def my_method; ‘hello '; end
end

obj = Object.new
#Object extension
obj.extend MyModule
obj.my_method # => “hello”
#Class extension
class MyClass
  extend MyModule
end

MyClass.my_method # => “hello”

Object # extend is a shortcut method for including modules in the receiver's singleton class.

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.