Methods of class and extension of classes in Ruby Object-oriented programming _ruby topics

Source: Internet
Author: User
Tags extend instance method

Class method

The essence of a class method is a single piece method that lives in a single piece of the class. There are three ways to define them, respectively:

# method One
def Myclass.a_class_method end


# Two
class MyClass
  def self.anther_class_method


# Method III *
class MyClass
  class << self
    def yet_another_class_method


The third way out, the essence of the class method, special memory!

Class extension

Class extensions define class methods by adding modules to the class's monolithic classes.

Module MyModule
  def My_method; ' Hello '; End
-

class MyClass
  class < self
    include mymodule
  end

myclass.my_ Method

The code above shows the implementation of the specific class extension, introducing a MyModule module into the MyClass class, because the My_method method is an instance method of the MyClass Singleton class, so the My_method method is also a MyClass class method.

Object extension

A class method is a special case of a single piece of method, so it is possible to apply a class extension to any object, which is an object extension

# method One: Open a single piece class to extend
module MyModule
  def My_method; ' Hello '; 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
#对象扩展
obj.extend mymodule
obj.my_method  # => "Hello" 
#类扩展
class MyClass
  extend MyModule
end

Myclass.my_method # => "Hello"

Object#extend is a fast-key way of including modules in the recipient's single piece 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.