方法 是执行特定任务并返回结果的语句集合。方法允许用户重用代码,而无需重新键入代码。方法可以节省时间,并帮助用户在不重新键入代码的情况下重用代码。
null
定义和调用方法: 在Ruby中,该方法在 def 关键字后跟 方法名称 以 终止 关键词。调用前必须定义一个方法,并且该方法的名称应为小写。方法只需按其名称进行调用。只要在调用方法时写下方法的名称即可。
语法:
def method_name # Statement 1 # Statement 2 . . end
例子:
# Ruby program to illustrate the defining # and calling of method #!/usr/bin/ruby # Here geeks is the method name def geeks # statements to be displayed puts "Welcome to GFG portal" # keyword to end method end # calling of the method geeks |
输出:
Welcome to GFG portal
将参数传递给方法: 在Ruby中,参数传递类似于其他编程语言的参数传递,即只需将参数写入括号()。
语法:
def method_name(var1, var2, var3) # Statement 1 # Statement 2 . . end
例子:
# Ruby program to illustrate the parameter # passing to methods #!/usr/bin/ruby # geeks is the method name # var1 and var2 are the parameters def geeks (var1 = "GFG" , var2 = "G4G" ) # statements to be executed puts "First parameter is #{var1}" puts "First parameter is #{var2}" end # calling method with parameters geeks "GeeksforGeeks" , "Sudo" puts "" puts "Without Parameters" puts "" # calling method without passing parameters geeks |
输出:
First parameter is GeeksforGeeks First parameter is Sudo Without Parameters First parameter is GFG First parameter is G4G
参数数量可变: Ruby允许程序员定义一个可以接受可变数量参数的方法。当用户在定义方法时不知道要传递的参数数量时,它很有用。
语法:
def method_name(*variable_name) # Statement 1 # Statement 2 . . end
例子:
# Ruby program to illustrate the method # that takes variables number of arguments #!/usr/bin/ruby # defining method geeks that can # take any number of arguments def geeks (*var) # to display the total number of parameters puts "Number of parameters is: #{var.length}" # using for loop for i in 0 ...var.length puts "Parameters are: #{var[i]}" end end # calling method by passing # variable number of arguments geeks "GFG" , "G4G" geeks "GeeksforGeeks" |
输出:
Number of parameters is: 2 Parameters are: GFG Parameters are: G4G Number of parameters is: 1 Parameters are: GeeksforGeeks
方法中的Return语句: Return语句,用于返回一个或多个值。默认情况下,方法始终返回在方法体中计算的最后一条语句。”return’关键字用于返回语句。
例子:
# Ruby program to illustrate method return statement #!/usr/bin/ruby # geeks is the method name def num # variables of method a = 10 b = 39 sum = a + b # return the value of the sum return sum end # calling of num method puts "The result is: #{num}" |
输出:
The result is: 49
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END