Ruby single-state method analysis

Source: Internet
Author: User

The behavior of an object depends on its class, but we often know that a specific object requires a specific behavior. in many languages, we have to get into the trouble of defining another class, even if it is only used for the next ing. in Ruby, we can assign any object a method of its own.

Ruby> class singletontest
| Def size
| Print "25 \ n"
| End
| End
Nil
Ruby> test1 = singletontest. New
# <Singletontest: 0xbc468>
Ruby> Test2 = singletontest. New
# <Singletontest: 0xbae20>
Ruby> def test2.size
| Print "10 \ n"
| End
Nil
Ruby> test1.size
25
Nil
Ruby> test2.size
10
Nil

In this example, test1 and Test2 belong to the same class, but Test2 has been assigned to an overloaded size method, so they have different behaviors. a method that only belongs to an object is called a single-state method.

The single-state method is often used for the design of graphical user interface (GUI) elements, where different buttons are pressed to stimulate different events.

The single-state method is not Ruby's patent. It also appears in Clos, Dylan, and other languages. at the same time, some languages, such as Self and newtonscript, have only single-State methods. they are sometimes called prototype-based languages.

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.