Ruby, as an object-oriented language, must be involved in the operation of objects, this time it involves methods.
Call Method-Object. Method Name (argument 1, Argument 2, ..., argument N)
Classification of methods:
1. Instance method: As the name suggests, is the method called by the instance. For example, "Ten, A". Split (",")
2. Class method: is the method called by the class. When you create an instance, you need to invoke the class method.
Copy Code code as follows:
A = Array.new #创建一个新数组
File.rename (Oldname, NewName) #更改文件名
When you invoke a class method, you can use ".", or you can use "::"
3. Function method: omit the caller's method directly. For example, sin (3.14), Sleep (m), print ("hello!")
To define a method:
Copy Code code as follows:
=begin
Syntax: Def method Name (parameter 1, parameter 2, ...) )
The action you want to perform
End
=end
def hello (name)
Print ("Hello,", name, ". \ n")
End
Hello ("Ruby") # =>hello, Ruby.
#可以为参数指定预设值
def hello (name= "Ruby")
Print ("Hello,", name, ". \ n")
End
Hello () # =>hello, Ruby.
Hello ("newbie") # =>hello, newbie.
#当方法中不止一个参数时, preset values must be specified starting at the right end of the argument
def func (A, b=1, c=2) # There are two parameters can be omitted, then should be designed to the right 2 can be omitted
.....
End
The return value of the method
similar to the Java language, you can use return to specify the returned value. You can use the return statement directly in the method to get the method results back.
Copy Code code as follows:
def volume (x,y,z)
Return x*y*z
End
P Volumne (2,3,4) # => 24
In the Ruby language, the return statement can also be omitted, at which point the calculated value of the last statement in the method is the returned value.
Copy Code code as follows:
def area (x, Y, z)
XY = X*y
YZ = Y*z
XZ = X*z
(xy + yz + xz) *2
End
P Area (2, 3, 4) # => 52
If there is a logical structure such as If...else, the return is omitted, not necessarily as the value of the last statement, but rather according to the current logical structure to see the statement executed.
If you want to jump out of a method directly in some cases, you can add a return statement.
Note: If the argument following the return is omitted, the nil is returned (equivalent to NULL in Java.)