Ruby Module---modules, components

Source: Internet
Author: User

  • The main purpose of module is to put different methods and constants into different namespaces.
  • The module is named in the same initial capitalization as the class, with multiple words without underlining. such as: Circlearea
  • Module syntax
    Module ModuleName
    ......
    End
  • The module uses the scope resolution operator "::" to invoke methods and constants in the module. For example:math::P i, math is the module name.
  • Ways to import Modules:
    1. Require ' module '-----import module.
    Such as: Require ' date ', importing the date module, but not require ' date '
    The module name and scope resolution operators are used when calling methods and constants in module, such as math::P I

    2. Include module names, such as include Math
    Calling methods and constants in a module does not require the Write module name and scope resolution operator to be called directly. such as: cos (), without the need to write Math::cos ()
  • you can think of module as a class that cannot be instantiated, cannot be inherited, and can be emulated with classes to implement multiple inheritance

    Module Martialarts
    Def Swordsman
    Puts "I ' m a swordsman."
    End
    End

    Class Ninja
      Include Martialarts
    Def initialize (clan)
    @clan = Clan
    End
    End

    Class Samurai
      Include Martialarts
    Def initialize (shogun)
    @shogun = Shogun
    End
    End

  • The Include keyword lets an instance use the methods and constants in the model, and the Extend keyword allows the class to use the methods and constants in the model itself

    Module Thepresent
    def now
    Puts "It ' s #{time.new.hour > 12? Time.new.hour-12:time.new.hour}:#{time.new.min} #{time.new.hour > 12? ' PM ': ' AM '} (GMT). "
    End
    End

    Class Thehereand
      Extend Thepresent
    End

    Thehereand.now

Ruby Module---modules, components

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.