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