Ruby Learning Module

Source: Internet
Author: User

We can think that module is a toolbox dedicated to storing a series of methods and constants.

The module and class are very similar, but the module cannot create an instance or have sub-classes. They can only store things.

For example:

module Circle  PI = 3.141592653589793    def Circle.area(radius)    PI * radius**2  end    def Circle.circumference(radius)    2 * PI * radius  endend

Module writing format

module ModuleName    #end

Just like a class name, the module name also uses uppercase letters without the underscore _.

One of the main functions of the module is to separate methods and constants into a namespace, which is called namespacing. This will not confuse Math :: pi and circle: Pi are two different PI values. Two colons: called the range resolution operator, which is used to tell Ruby where to find the value or method we need. If we want to find Math: PI, ruby knows to go to the math module to find pi.

 

Some modules are already included in the Ruby interpreter, but some need to be explicitly included. We can use the keyword require, as shown below:

require "module"

If we want to use Ruby's date module to display today's date, but we haven't included it with require, we need to perform the following operations:

require "date"puts Date.today

 

Of course we can use require to include more modules, but we can also use the include keyword.

If any class includes a module, this class can use this module method.

One advantage of using include is that we no longer have to write the module name containing constants or methods, because all information in the module has been included in the class of the include module, we can directly use PI instead of Math: PI, as shown below:

class Angle  include Math  attr_accessor :radians    def initialize(radians)    @radians = radians  end    def cosine    cos(@radians)  endendacute = Angle.new(1)acute.cosine

 

Ruby Learning Module

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.