Ruby 方法的定义与使用
1. 定义简单方法
在 Ruby 中,方法使用 def 关键字来定义。定义方法时, def 后面跟着方法名,接着是可选的参数列表,参数列表放在括号中。方法体由 Ruby 代码构成,跟在参数列表之后,方法的结束用 end 关键字标记。参数名可以在方法体中作为变量使用,这些命名参数的值来自方法调用时的参数。
以下是一个示例方法:
# Define a method named 'factorial' with a single parameter 'n'
def factorial(n)
if n < 1 # Test the argument value for validity
raise "argument must be > 0"
elsif n == 1 # If the argument is 1
1 # then the value of the method invocation is 1
else # Otherwise, the factorial of n is n times
n * factorial(n-1) # the factorial of n-1
end
end
这个代码定义了一个名为 factorial 的方法,该方法有一
超级会员免费看
订阅专栏 解锁全文
517

被折叠的 条评论
为什么被折叠?



