Modules and blocks are special in ruby.
The module has a namespace to organize classes, methods, and constants.
Module also has the Mixin method. You can include a module in the class to implement the instance method mixed into a module.
Sample: Module msample
Pi = 1
Def Self. Say
Puts " Static hi "
End
Def Say
Puts " Instance hi "
End
Class Inner
Include msample # Mixin module msample
End
End
Class Sample
Include msample # Mixin module msample
End
Msample: pi = 5
Puts msample: PI. to_s # Put "5"
Msample. Say # Put "static hi"
Puts msample. Class # Put "module"
(Sample. New). Say # Put "instance hi"
(Msample: inner. New). Say # Put "instance hi"
Block isCodeBlock, such
{
...
}
Do
...
End
All are code blocks. When calling a function, you can not only input parameters, but also code blocks and use yield to call them. For example: Def Repeateputline (number)
Number. Times { | N |
Puts " # {N + 1}. # {yield} "
}
End
Repeateputline ( 5 ){ " Hallo " }
The code block can not only be anonymous, but also be assigned to a handle, for example Def Repeateputline (number)
Number. Times { | N |
Puts " # {N + 1}. # {yield} "
}
End
H = Proc. New {
" Hallo "
}
Repeateputline ( 5 ) {H. Call}
The above H is called a process object in Ruby and can be regarded as a handle of a code block. when calling the code in a process object, call the call method of the process object, process objects are equivalent to lambda expressions in other languages, but they are more flexible and powerful than lambda expressions.
Generally, the process object is not created using Proc. New and can be directly created using proc, as shown in Def Repeateputline (number)
Number. Times { | N |
Puts " # {N + 1}. # {yield} "
}
End
H = Proc {
" Hallo "
}
Repeateputline ( 5 ) {H. Call}
In fact, the best application example of code blocks is the array each, collect, map and other methods, all of which apply anonymous code blocks.
(1 .. 5). Each {| I | puts "# {I}. Hallo "}
Simple Example of a process object P=Proc {|ARG|Puts Arg}
P. Call ("Hello")