Ruby 中的调用方法
Nurudeen Ibrahim
2023年1月30日
Ruby
Ruby Method
Ruby 的 call 方法用于 Procs。要了解 Proc,我们首先需要了解 Block。
Ruby blocks 是包含在 do-end 语句或花括号 {} 中的匿名函数。
Proc 块可以存储在一个变量中,传递给一个方法或另一个 Proc,并使用 call 方法独立调用。
以下是创建 Proc 的不同方法。
在 Ruby 中创建一个 Proc 类
square_proc = Proc.new { |x| x**2 }
puts square_proc.call(4)
输出:
16
在上面的例子中,我们争论了 call 方法,因为 square_proc 定义了一个参数 x。
如果我们没有在 Proc 中定义任何参数,我们就不需要在调用 proc 时将任何参数传递给 call。
不过,这不是一个很好的案例。下面是另一个未定义参数的示例。
empty_proc = Proc.new { 4 * 4 }
puts square_proc.call
输出:
16
在 Ruby 中使用 proc 关键字
multiplication_proc = proc { |x, y| x*y }
puts multiplication_proc.call(4, 5)
输出:
20
上述方法展示了如何创建 regular Procs。Proc 还有另一种风格,叫做 lambda。
Procs 和 Lambdas 通常可以互换使用,尽管有一些区别。下面的方法展示了如何创建这种称为 lambda 的 procs 风格。
在 Ruby 中使用 lambda 关键字
square_lambda = lambda { |x| x**2 }
puts square_lambda.call(5)
输出:
35
在 Ruby 中使用 lambda 文字语法
multiplication_lambda = ->(x, y) { x*y }
puts multiplication_lambda.call(5, 6)
输出:
30
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe