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