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 also has applications similar to C # delegate, Which is simpler and directly expressed in, in addition, Ruby uses a keyword called yield to notify the interpreter to execute the passed code block 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