1, Ruby in the method name and variable name rules ( beginning with lowercase letters, the separation between words using "_",), but you can take the method name behind! (blockbuster method) or? (A Boolean type returns a value).
2, the method of the parameters, please use (), parameters are local variables, you can set the default values for these parameters, the parameter with "*" is an optional dynamic parameter, you can pass in one or more, if there are normal parameters, there are optional parameters, optional parameters should be placed at the end, such as the following sample code.
Copy Code code as follows:
def read_book (chinese= ' Water Margin ', english= ' Jane Eyre ', *others)
Puts "Chinese book: #{chinese},english book:#{english}"
Temp= '
Others.each do |o|
temp<<o<< '
End
Puts "Other optional books: #{temp}"
End
Read_book
# Output: Chinese books: Outlaws of the Marsh, 中文版 Book:jane Eyre
Read_book (' Journey to the Westward ', ' Rails ', ' dream of Red Mansions ', ' The Romance of the Kingdoms ', ' seal the Gods ', ' Sui and Tang Kingdoms ')
Output
# Chinese books: Journey to the East, 中文版 book:rails
# Other alternative books: The Romance of the Red Mansions Romance of the Sui and Tang dynasties
3, the return value of the method does not need to be declared, by default, the last line of code is the return value , but if there is a condition to determine the situation returned, you need to use the return declaration, the following sample code:
Copy Code code as follows:
def late_for_work? (minutes)
return True if minutes>=15
False
End
Late_for_work? (a) #false
Late_for_work? (#true)
4, the heavy method refers to the method name after the band! method, the normal method returns a copy of the original object , and the heavy method returns always the original object itself, such as the following sample code:
Copy Code code as follows:
x= ' Hello '
Y=x.upcase
Puts ' x:#{x},y:#{y} ' #输出: X:hello,y:hello x value not changed
x= ' Hello '
y=x.upcase!
Puts "X:#{x},y:#{y}" #输出: X:hello,y:hello x's value has changed
5, the method can use the alias keyword "alias" to generate a copy of the method, even if the original method has changed, the alias copy will not change, the following sample code:
Copy Code code as follows:
def Show_alias
Puts ' before alias! '
End
Alias Alias_foo Show_alias
def Show_alias
Puts ' after alias! '
End
Show_alias #输出: After alias!
Alias_foo #输出: Before alias!
6, Ruby method can return multiple values at one time, but in essence only the surface appears to return multiple values, essentially returns an array, the array store multiple return values, can be directly defined by the receipt of multiple variables, the following sample code:
Copy Code code as follows:
def More_result_foo
X=5
Y=x*x
Z=y-x+2
Return x,y,z #返回x, y,z three values
End
A,b,c=more_result_foo #a, B,c receives the returned X,Y,Z
M=more_result_foo #m接收返回的x, Y,z
Puts A,b,c #输出: 5 25 22
Puts M #输出: 5 25 22
Puts M.class #输出: Array