I. Method
Ruby's method definition allows setting default values for parameters, but parameters without default values cannot appear after parameters with default values (allowing * and &), which means that the following method definitions are not allowed, explain A parse error occurs. Another difference from C # is that method definitions cannot appear after method calls.
# parse error
def Display (args1 = "proshea", args2)
end
# Allow
def Display (args1 = "proshea", * args2)
end
# Allow
def Display (args1 = "proshea", & args)
end
Show ()
# Appears wrong after Show call
def Show
end
Ruby also supports parameter functions like C # params, except that Ruby uses * to mark it.
def Display (* args)
print% Q ~ # {args.join ("-")} ~
end
# proshea-32-WinForm
Display ("proshea", 32, "WinForm")
Similarly, Ruby also has an application similar to the C # delegate, but it is simpler and is directly expressed by &. Ruby uses a keyword called yield to tell the interpreter to execute the passed code block or Proc object ?).
1def Display (& block)
2 if block_given?
3 yield (block)
4 else
5 print% Q ~ no process object passed in ~
6 end
7end
8
9def Show ()
10 print% Q ~ Show method call ~
11end
12
13 # No incoming process object
14Display ()
15 # Call Show method inside Display
16 # Note that the opening brace can still only be on the same line as the method name
17Display () {
18 Show ()
19}