I. Methods
The ruby method definition allows you to set default values for parameters. However, parameters without default values (* and &) cannot be followed by parameters with default values &), that is to say, the following method definition is not allowed. parse error occurs during interpretation. Another difference from C # Is that the method definition cannot appear after the method call.
# Parse errordef display (args1 = "proshea", args2) end # Allow def display (args1 = "proshea", * args2) end # Allow def display (args1 = "proshea ",& ARGs) Endshow () # def showend, which is incorrect after the show call
Ruby also supports parameter functions such as C # Params, but Ruby uses the * identifier.
Def display (* ARGs) print % Q ~ # {Args. Join ("-")}~ End # proshea-32-WinFormDisplay ("proshea", 32, "winform ")
Similarly, Ruby has applications similar to C # Delegate, Which is simpler and directly expressed in &. Ruby uses a keyword called yield to notify the interpreter to execute the inputCodeBlock or proc object (process object ?).
1def display (& Block) 2 if block_given? 3 yield (Block) 4 else5 print % Q ~ No process object passed in ~ 6 end7end89def show () 10 print % Q ~ Show method call ~ 11end1213 # No process object passed in 14 display () 15 # Call show Method 16 in display # note that the starting braces can only be 17 display () {18 show () in the same row as the method name () 19}
Block_given? Is the method defined in the internal module kernel to indicate whether the proc object is passed in. Later, Ruby uses the yield notification interpreter to execute the passed-In Proc. A process object can also contain parameters. Different from a common method, the parameters of a process object are in a set of |. You can use the call method of Proc object to call a process object with parameters.
1 class employee2 def initialize (username, age,& Block) 3 @ username, @ age, @ block = username, age, block4 end56 def display (txt) 7 # Although @ block is an instance variable, however, you must add 8 print braces "# {@ block. call (txt) }:# @ username-# @ age "9 end10end1112emp = employee. new ("proshea", 32) {13 | TXT | 14 txt15} 16emp. display ("context ")
1