1. 定义方法:
def greet(name)
puts "Hello, #{name}!"
end
在上面的例子中,greet 是方法的名称,(name) 是参数列表。方法体位于 def 和 end 之间。
2. 调用方法:
greet("Alice")
在上面的例子中,我们调用了 greet 方法,并传递了一个参数 "Alice"。
3. 默认参数值:
def greet(name="Guest")
puts "Hello, #{name}!"
end
在上面的例子中,name 参数有一个默认值为 "Guest"。如果调用时未提供参数,将使用默认值。
4. 可变数量的参数:
def sum(*numbers)
total = 0
numbers.each { |num| total += num }
puts "Sum: #{total}"
end
在上面的例子中,*numbers 允许方法接受任意数量的参数,并将它们存储在一个数组中。
5. 返回值:
def add(a, b)
result = a + b
return result
end
在上面的例子中,return 关键字用于返回方法的结果。在 Ruby 中,最后一个表达式的值将被隐式返回,因此可以省略 return。
6. 带块的方法:
def execute_block
puts "Start of method"
yield if block_given?
puts "End of method"
end
execute_block do
puts "Inside the block"
end
在上面的例子中,yield 用于调用与方法一起传递的块。
7. 类方法:
class MathOperations
def self.square(num)
num * num
end
end
result = MathOperations.square(5)
puts "Square: #{result}"
在上面的例子中,self.square 是一个类方法,可以通过类直接调用,而不需要创建类的实例。
这些是 Ruby 中定义和调用方法的基本概念。方法是 Ruby 中的一个核心概念,它们使代码更加模块化、可重用,并提高了代码的可读性。
转载请注明出处:http://www.zyzy.cn/article/detail/13428/Ruby