Code blocks in ruby are used as method parameters.

Source: Internet
Author: User

The ruby method can accept code blocks as parameters, which is a very flexible method and a very good design idea. Suppose there are three methods as shown in 1:

Figure 1

As shown in figure 1, a large number of code blocks of method A, Method B, and method C are identical. Do you need to define three methods? Is there a better way?
In the software development field, there is an important dry rule: Do not repeat. In the three methods shown in figure 1, we can find that they contain a large number of repeated code. To this end, we combine the above three methods into one method, the specific code block in the three methods is passed as a parameter, as shown in step 2.


Figure 2

As shown in figure 2, you can use a code block as a parameter to replace multiple methods with one method, so as to provide better code reuse and ensure better Software maintainability.

Sample Code:

@ Testdata = array. New
@ Testdata <"Sun Wukong"
@ Testdata <""

Def make (thing)
Puts "Preparations"
Yield (thing)
Puts "receiving action"
End

Def pp (key1, key2)
Puts key1 + "and" + key2
End

Make (@ testdata) {| A |
PP (*)
}

Make ("") {| A |
Puts
}

Make ("Tang Seng") {| A |
Puts
}

Running result:

Preparations

Sun Wukong and pig

Receiving action

Preparations

Pig

Receiving action

Preparations

Tang Seng

Receiving action

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.