Mixin for Ruby Learning

Source: Internet
Author: User

Directly run the Code:

Module action def jump @ distance = rand (4) + 2 puts "I jumped forward # {@ DISTANCE} feet! "Endendclass rabbit include action attr_reader: Name def initialize (name) @ name = Name endclass cricket include action attr_reader: Name def initialize (name) @ name = Name endendpeter = rabbit. new ("Peter") Jiminy = cricket. new ("Jiminy") Peter. jumpjiminy. jump ---------------------------------------------------------------------- output: I jumped forward 3 feet! I jumped forward 4 feet! Nil

Module for Ruby learning has introduced Module

When a module is used to mix some behaviors and information into a class, this behavior is called Mixin.

Mixin allows us to customize a class without rewriting this class.

The above Code uses Mixin.

The jump method is defined in the action module. The action is included in the rabbit and cricket classes, so these two classes have the jump method. Therefore, the rattit and cricket instances peter And Jiminy can call jump.

You may have discovered that Mixin gives us the multi-inheritance capability of similar classes. With the Mixin technique, we can extract many behaviors from many modules and add them to our classes.

 

Mixin for Ruby Learning

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.